Showing posts with label VBA Teacher Sourav. Show all posts
Showing posts with label VBA Teacher Sourav. Show all posts

Wednesday, April 27, 2022

Convert multiple contiguous columns as one single column maintaining their(rows and columns) order using VBA

   

Dim wb As Workbook

 Set wb = ActiveWorkbook

 Dim wf As Worksheet


With wb
    For Each oSheet In .Sheets

        If oSheet.Name = "verticalmm" Then
            oSheet.Delete
            
          
            
            
            
            

        End If
Next oSheet
    Set wf = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    wf.Name = "verticalmm"
    End With
    
    
' wb.Close savechanges:=True
   
   
    Dim Range1 As Range, Range2 As Range, Rng As Range
    Dim rowIndex As Integer
    we.Select
    
    Range("B2").Select
    If ActiveCell.Offset(1, 0).Value <> "" Then
    
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Else
    Exit Sub
    End If
    
   Set Range1 = Application.Selection
   'Set Range1 = Application.InputBox("Source Ranges:", xTitleId, Range1.Address, Type:=8)
     'Set Range2 = Application.InputBox("Convert to (single cell):", xTitleId, Type:=8)
     Set Range2 = wf.Range("A1")
     'we.Select
     For Each Rng In Range1.Rows
    Rng.Copy
    Range2.Offset(rowIndex, 0).PasteSpecial Paste:=xlPasteAll, Transpose:=True
    rowIndex = rowIndex + Rng.Columns.Count
Next
Application.CutCopyMode = False
wf.Select

Dim last_row As Long

    last_row = Cells(Rows.Count, 1).End(xlUp).Row
    'MsgBox (last_row)
    
    Columns("A:A").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "0"
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "1"
    Range("A1:A2").Select
    Selection.AutoFill Destination:=Range("A1:A" & last_row)
    
   
   wb.Close savechanges:=True

 

 

Source:https://www.extendoffice.com/documents/excel/1172-excel-transpose-multiple-columns-into-one-column.html

Thursday, April 14, 2022

Printing filtered data and stopping printing blank pages and fitting all columns in one page using vba

 Sub justprint()

Sheets("Sheet1").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    On Error Resume Next
    ActiveSheet.ShowAllData
End If









'let us first delete anysheet containing name like Canada and create sheets named as Canada

 With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
   
Dim wks, newsheet As Worksheet


For Each wks In Application.Worksheets
        If wks.name = "Canada" Then wks.Delete
    Next



 Dim cntsheets As Long
 
     cntsheets = Application.Sheets.Count
    Set newsheet = Application.Worksheets.Add(After:=Worksheets(cntsheets))
    newsheet.name = "Canada"

   

'Now creating sheets is done ,let us go back the data sheet and remove any filter from the sheet
'creating the directory for pdf files

Dim output_file As String, ws_count, i As Integer
Dim path, folder As String
path = "C:\Users\allso\Desktop\excel_to_pdf_2"
folder = dir(path, vbDirectory)
If folder = vbNullString Then

       
                VBA.FileSystem.MkDir (path)
          

    Else

    

    End If
    
Sheets("Sheet1").Select

Dim mynetwork As Object


Dim dataforfilter As String
Dim strtime As String
'set current default printer
Set mynetwork = CreateObject("WScript.network")
mynetwork.setdefaultprinter "Adobe PDF"
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
Dim prtLoop As Object
'get current default printer
Set prtLoop = objAccess.Printer
'now we can access the printquality supported by the default printer by using prtloop.printquality

dataforfilter = Replace(ActiveSheet.Range("A1").CurrentRegion.Address, "$", "")
'MsgBox (dataforfilter)
ActiveSheet.Range(dataforfilter).AutoFilter Field:=2, Criteria1:="Canada", Operator:=xlFilterValues
'ActiveSheet.Range(dataforfilter).AutoFilter Field:=4, Criteria1:="=Yes", Operator:=xlFilterValues
'sort the filtered range by the column gross sales
dataforfilter = Replace(ActiveSheet.Range("A1").CurrentRegion.Address, "$", "")
'MsgBox (dataforfilter)
Range(dataforfilter).Sort key1:=[h2], Order1:=xlDescending, Header:=xlYes
ActiveSheet.Range("A1").CurrentRegion.Select
Selection.Copy

Sheets("Canada").Select
'Range("A1").PasteSpecial xlPasteValues

Range("A1").PasteSpecial xlPasteAllUsingSourceTheme, Operation:=xlNone _
        , SkipBlanks:=False, Transpose:=False
        
'autofitting the columns
ActiveSheet.Cells.Columns.AutoFit
'removing the borders
'changing the font
 With ActiveSheet.Cells.Font
 
        .name = "Georgia Pro"
        .Size = 11
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .TintAndShade = 0
        .ThemeFont = xlThemeFontNone
    End With

ActiveSheet.Cells.Borders.LineStyle = xlLineStyleNone

'now saving the sheet as pdf


If Format(CDate(Now), "am/pm") = "am" Then
strtime = Format(Now(), "yyyymmdd\_hhmmss") & " AM"
Else
strtime = Format(Now(), "yyyymmdd\_hhmmss") & " PM"
End If

output_file = path & "\" & Left(ThisWorkbook.name, Len(ThisWorkbook.name) - 5) & "." & ActiveSheet.name & "." & strtime & ".pdf"

'setting the page setup

'ActiveSheet.PageSetup.CenterHeader = "&B&14" & "Financial Data for " & uniquedatafinal(length) & ""

'&""Courier New""

'determine it is am or pm

If Format(CDate(Now), "am/pm") = "am" Then


ActiveSheet.PageSetup.CenterHeader = "&B&14&""Arial Narrow""&K00B0F0" & "Financial Data for " & "Canada" & " on " & "&D" & "," & "&T" & " AM"
Else
ActiveSheet.PageSetup.CenterHeader = "&B&14&""Arial Narrow""&K00B0F0" & "Financial Data for " & "Canada" & " on " & "&D" & "," & "&T" & " PM"

End If

'this is for setting the right footer of print which will print as Page (number of current page) of Total Pages
ActiveSheet.PageSetup.RightFooter = "&B&10&""Arial Narrow""&K00B0F0" & "Page &P of &N"

'change activeprinter to a choice of mine

'to set printarea manually we have to calculate the printarea using this lastrow
Dim lastrow As Long

lastrow = Application.WorksheetFunction.Subtotal(3, Range("P:P"))

'this commented out section works best with portrait printing

With ActiveSheet.PageSetup
.CenterHorizontally = True
'.CenterVertically = True
.BottomMargin = 50
.TopMargin = 50
.RightMargin = 10
.LeftMargin = 10
'.Zoom = 50
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintTitleRows = ActiveSheet.Rows(1).Address
.Orientation = xlPortrait
.PrintQuality = prtLoop.PrintQuality
.PrintArea = "A1:P" & lastrow

End With
'MsgBox (ActiveSheet.PageSetup.PrintArea.Address)
'ActiveSheet.PrintPreview
'this section works best for landscape printing
'With ersheet.PageSetup
''for setting portrait or landscape
'.Orientation = xlLandscape
''these next two line will fit all columns in one page
'.FitToPagesWide = 1
'.FitToPagesTall = 1
''this line is responsible for continuing one fixed row on several print pages ,it is similar as excel freeze pane
'.PrintTitleRows = ersheet.Rows(1).Address
'End With
ActiveWorkbook.ActiveSheet.ExportAsFixedFormat xlTypePDF, output_file, xlQualityStandard, openafterpublish:=False
    
    
Sheets("Sheet1").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    On Error Resume Next
    ActiveSheet.ShowAllData
End If



If ActiveSheet.AutoFilterMode Then

     ActiveSheet.AutoFilterMode = False

End If

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With

End Sub


Source:https://stackoverflow.com/questions/25741049/how-to-set-fit-all-columns-on-one-page-in-print-tab


Source:https://stackoverflow.com/questions/17285897/row-count-on-the-filtered-data

Thursday, September 16, 2021

Send outlook mail from non primary account using VBA

 

   'Used with GetDefaultFolder of the NameSpace
    Public Const olFolderCalendar = 9 'The Calendar folder.
    Public Const olFolderConflicts = 19 'The Conflicts folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
    Public Const olFolderContacts = 10 'The Contacts folder.
    Public Const olFolderDeletedItems = 3 'The Deleted Items folder.
    Public Const olFolderDrafts = 16 'The Drafts folder.
    Public Const olFolderInbox = 6 'The Inbox folder.
    Public Const olFolderJournal = 11 'The Journal folder.
    Public Const olFolderJunk = 23 'The Junk E-Mail folder.
    Public Const olFolderLocalFailures = 21 'The Local Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
    Public Const olFolderManagedEmail = 29 'The top-level folder in the Managed Folders group. For more information on Managed Folders, see the Help in Microsoft Outlook. Only available for an Exchange account.
    Public Const olFolderNotes = 12 'The Notes folder.
    Public Const olFolderOutbox = 4 'The Outbox folder.
    Public Const olFolderSentMail = 5 'The Sent Mail folder.
    Public Const olFolderServerFailures = 22 'The Server Failures folder (subfolder of the Sync Issues folder). Only available for an Exchange account.
    Public Const olFolderSuggestedContacts = 30 'The Suggested Contacts folder.
    Public Const olFolderSyncIssues = 20 'The Sync Issues folder. Only available for an Exchange account.
    Public Const olFolderTasks = 13 'The Tasks folder.
    Public Const olFolderToDo = 28 'The To Do folder.
    Public Const olPublicFoldersAllPublicFolders = 18 'The All Public Folders folder in the Exchange Public Folders store. Only available for an Exchange account.
    Public Const olFolderRssFeeds = 25 'The RSS Feeds folder.

Sub setoutlookNS()

Dim olApp, olAccts As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim olNewMail As Outlook.MailItem
Set olNewMail = olFolder.Items.Add 'creating new mail
With olNewMail
'.SentOnBehalfOfName = """Sourav IT Faculty"" <allsourav@gmail.com>"
.To = "allsourav2@gmail.com;allsourav@gmail.com;"
.CC = "souravandamiya@gmail.com"

.Subject = "Happy Birthday on 14.09.2021"
.Body = "Wish you a happy birthday ,\n learning outlook using python again"
.Importance = 2
.ReadReceiptRequested = True
.OriginatorDeliveryReportRequested = True

Set olAccts = olApp.Session.Accounts
For Each olAcct In olAccts
If olAcct.SmtpAddress = "allsourav@gmail.com" Then
.SendUsingAccount = olAcct
Exit For
End If


Next olAcct
'MsgBox (olApp.Session.Accounts.Count)



.Display
.Send


End With

End Sub

Sunday, February 14, 2021

Get prices of the products from amazon and flipkart automatically using VBA

 Option Explicit

Sub Search()


Dim sh As Worksheet
Set sh = ActiveSheet

sh.Range("A1").Value = 1

Call Fetch_from_Amazon
    Application.Wait Now + TimeValue("0:00:10")
Call Fetch_from_Flipkart

MsgBox "Done"

End Sub

Sub Fetch_from_Amazon()
 
Dim sh As Worksheet
Set sh = ActiveSheet


Dim i As Integer

Dim IE As InternetExplorer
Dim html_doc As HTMLDocument

Set IE = New InternetExplorer

IE.Visible = True
IE.navigate "WWW.Amazon.in"
Application.Wait (Now + TimeValue("0:00:10"))

'Do Until IE.readyState = READYSTATE_COMPLETE
'    DoEvents
'Loop

''Do Until IE.readyState = 4
''        DoEvents
''    Loop
''
''    Application.Wait (Now + TimeValue("0:00:10"))
''
''    Do Until IE.readyState = 4
''        DoEvents
''    Loop
'
''Set the max time to load
'
'Dim maxLoadingTime As Single, myTimer As Single
'maxLoadingTime = 10     '< -- # of seconds to allow page to load -- <
'myTimer = Timer
'
'Do
'    DoEvents
'    If Timer >= maxLoadingTime + myTimer Then
'        Debug.Print Time & " Notice: Connection Error. Refreshing webpage"
'        IE.stop
'        IE.Refresh
'    End If
'Loop Until IE.readyState = 4


Set html_doc = IE.document

For i = 4 To sh.Range("A" & Application.Rows.Count).End(xlUp).Row
    DoEvents
    
    If sh.Range("A1").Value = 0 Then Exit Sub
    
    On Error Resume Next
    
    html_doc.getElementById("twotabsearchtextbox").Value = sh.Range("A" & i).Value
    html_doc.getElementsByClassName("nav-input")(1).Click
    
    Do Until IE.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop
    
    Application.Wait Now + TimeValue("0:00:02")
    
    sh.Range("B" & i).Value = html_doc.getElementsByClassName("a-size-medium a-color-base a-text-normal")(0).innerText
    sh.Range("C" & i).Value = html_doc.getElementsByClassName("a-price-whole")(0).innerText
     
Next i

IE.Quit


End Sub

Sub Fetch_from_Flipkart()

Dim sh As Worksheet
Set sh = ActiveSheet

Dim IE As InternetExplorer
Dim html_doc As HTMLDocument
Dim i As Integer

Set IE = New InternetExplorer

IE.Visible = True
IE.navigate "WWW.Flipkart.com"


Do Until IE.readyState = READYSTATE_COMPLETE
    DoEvents
Loop

'SendKeys "{ESC}"
'DoEvents

Set html_doc = IE.document

For i = 4 To sh.Range("A" & Application.Rows.Count).End(xlUp).Row

    If sh.Range("A1").Value = 0 Then Exit Sub
    
    DoEvents
    On Error Resume Next
    Dim searchtext As String
    
    html_doc.getElementsByClassName("_3704LK")(0).Value = sh.Range("A" & i).Value
    searchtext = sh.Range("A" & i).Value
    'html_doc.getElementsByClassName("L0Z3Pu")(0).Click
    'ie.navigate "http://www.bestbuy.com/site/searchpage.jsp?st=" & searchtext & "&_dyncharset=UTF-8&id=pcat17071&type=page&sc=Global&cp=1&nrp=&sp=&qp=&list=n&iht=y&usc=All+Categories&ks=960&keys=keys"
    IE.navigate "https://www.flipkart.com/search?q=" & searchtext & "&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&as-pos=1&as-type=HISTORY"
    Do Until IE.readyState = READYSTATE_COMPLETE
        DoEvents
    Loop
    
    Application.Wait Now + TimeValue("0:00:03")
    
    sh.Range("D" & i).Value = html_doc.getElementsByClassName("_4rR01T")(0).innerHTML
    sh.Range("E" & i).Value = html_doc.getElementsByClassName("_30jeq3 _1_WHN1")(0).innerHTML

Next i

IE.Quit

End Sub



Sub Clear_Sheet()

Dim sh As Worksheet
Set sh = ActiveSheet

sh.Range("B4:E" & Application.Rows.Count).ClearContents

End Sub


Sub Stop_Macro()

Dim sh As Worksheet
Set sh = ActiveSheet

sh.Range("A1").Value = 0

End Sub


I changed some code to make it work,however originally it was in this video


https://youtu.be/0JHbb5-elMU

Tuesday, December 8, 2020

Send gmail with embedded picture in mail body using VBA

 'For Early Binding, enable Tools > References > Microsoft CDO for Windows 2000 Library
Option Explicit

Sub SendEmailUsingGmail()
    Dim NewMail As Object
    Dim mailConfig As Object
    Dim subj As String
    
    Dim fso As Object
    
    Dim fields As Variant
    Dim msConfigURL As String
    Dim rng As Range
    
    Workbooks.Open "C:\Users\allso\Desktop\new vba projects\new project subham brother\DPR NOV 2020.xlsb"
    subj = Workbooks("DPR NOV 2020.xlsb").sheets("ZONE").Range("H1").Value
    Workbooks("DPR NOV 2020.xlsb").Close SaveChanges:=True
   Set rng = Nothing
    On Error Resume Next

   ' Set rng = Selection.SpecialCells(xlCellTypeVisible)

    On Error GoTo Err:

    'late binding
    Set NewMail = CreateObject("CDO.Message")
    Set mailConfig = CreateObject("CDO.Configuration")
    Const cdoRefTypeId = 0

    Set fso = CreateObject("Scripting.FileSystemObject")
    ' load all default configurations
    mailConfig.Load -1

    Set fields = mailConfig.fields
    
    

    
 
    'Set All Email Properties
    With NewMail
        .AutoGenerateTextBody = False
        .Sender = "allsourav2@gmail.com"
        .From = "Sourav Bhattacharya"
        .To = "" 'mail address
        .CC = ""
        .BCC = ""
        .Subject = subj
        .BodyPart.ContentTransferEncoding = "quoted-printable"
        .BodyPart.Charset = "utf-8"
        '.Textbody = "Let me know if you have questions about the attached spreadsheet!"
         ' Adding images as inline attachments with Content IDs which is used with image sources. e.g. <img src="cid:image1" .. >
        .AddRelatedBodyPart fso.GetAbsolutePathName("C:\Users\allso\Desktop\new vba projects\temp1.jpg"), "temp1", cdoRefTypeId
        .AddRelatedBodyPart fso.GetAbsolutePathName("C:\Users\allso\Desktop\new vba projects\temp2.jpg"), "temp2", cdoRefTypeId
        '.Addattachment "C:\Users\allso\Desktop\new vba projects\temp.jpg"
        '.HTMLBody = .Textbody & "<html><p>CPS Daily progress Report of Nov 2020</p>" & _
                "<img src=""cid:temp.jpg"" height='600' width='900'>"
        'append html body from file
        .HTMLBody = fso.OpenTextFile("C:\Users\allso\Desktop\new vba projects\temp.html").ReadAll
    End With

    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"

    With fields
        .Item(msConfigURL & "/smtpusessl") = True             'Enable SSL Authentication
        .Item(msConfigURL & "/smtpauthenticate") = 1          'SMTP authentication Enabled
        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
        .Item(msConfigURL & "/smtpserverport") = 465          'Set the SMTP port Details
        .Item(msConfigURL & "/sendusing") = 2                 'Send using default setting
        .Item(msConfigURL & "/sendusername") = "" 'Your gmail address
        .Item(msConfigURL & "/sendpassword") = "" 'Your password or App Password
        .Update                                               'Update the configuration fields
    End With
    
    
    NewMail.Configuration = mailConfig
    
    
    NewMail.Send
    
    MsgBox "Your email has been sent", vbInformation

Exit_Err:
    'Release object memory
    Set NewMail = Nothing
    Set mailConfig = Nothing
    Set fso = Nothing
    
    End

Err:
    Select Case Err.Number
    Case -2147220973  'Could be because of Internet Connection
        MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
    Case -2147220975  'Incorrect credentials User ID or password
        MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
    Case Else   'Report other errors
        MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
    End Select

    Resume Exit_Err

End Sub



temp.html file contains



<img src="cid:temp1" alt="SpaceImage" title="first image" style="display: block" width="900" height="550" />
<img src="cid:temp2" alt="HostImage" title="second image" style="display: block" width="900" height="1000" />



Send gmail using VBA with attachment

 Option Explicit

Sub SendEmailUsingGmail()
    Dim NewMail As Object
    Dim mailConfig As Object
    Dim fields As Variant
    Dim msConfigURL As String
    Dim rng As Range
   Set rng = Nothing
    On Error Resume Next

    Set rng = Selection.SpecialCells(xlCellTypeVisible)

    On Error GoTo Err:

    'late binding
    Set NewMail = CreateObject("CDO.Message")
    Set mailConfig = CreateObject("CDO.Configuration")

    ' load all default configurations
    mailConfig.Load -1

    Set fields = mailConfig.fields
    
    

    
 
    'Set All Email Properties
    With NewMail
        .Sender = "" 'mail address
        .From = "Sourav Bhattacharya"
        .To = "" 'mail address
        .CC = ""
        .BCC = ""
        .Subject = "Demo Spreadsheet Attached"
        .Textbody = "Let me know if you have questions about the attached spreadsheet!"
        .Addattachment "C:\Users\allso\Desktop\new vba projects\temp.jpg"
        .HTMLBody = .Textbody
      
    End With

    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"

    With fields
        .Item(msConfigURL & "/smtpusessl") = True             'Enable SSL Authentication
        .Item(msConfigURL & "/smtpauthenticate") = 1          'SMTP authentication Enabled
        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com" 'Set the SMTP server details
        .Item(msConfigURL & "/smtpserverport") = 465          'Set the SMTP port Details
        .Item(msConfigURL & "/sendusing") = 2                 'Send using default setting
        .Item(msConfigURL & "/sendusername") = "" 'Your gmail address
        .Item(msConfigURL & "/sendpassword") = "" 'Your password or App Password
        .Update                                               'Update the configuration fields
    End With
    
    
    NewMail.Configuration = mailConfig
    NewMail.Send
    
    MsgBox "Your email has been sent", vbInformation

Exit_Err:
    'Release object memory
    Set NewMail = Nothing
    Set mailConfig = Nothing
    End

Err:
    Select Case Err.Number
    Case -2147220973  'Could be because of Internet Connection
        MsgBox "Check your internet connection." & vbNewLine & Err.Number & ": " & Err.Description
    Case -2147220975  'Incorrect credentials User ID or password
        MsgBox "Check your login credentials and try again." & vbNewLine & Err.Number & ": " & Err.Description
    Case Else   'Report other errors
        MsgBox "Error encountered while sending email." & vbNewLine & Err.Number & ": " & Err.Description
    End Select

    Resume Exit_Err

End Sub



Convert excel range to a picture using VBA

 Option Explicit


Sub Exportrangetopicture(oWs As Worksheet, rng As String, num As Integer)
'Hides alerts
 Application.DisplayAlerts = False
 'Dim oWs As Worksheet
 Dim oRng As range
 Dim oChrtO As ChartObject
 Dim lWidth As Long, lHeight As Long

 'Set oWs = sheets("AREA")
 
 Set oRng = oWs.range(rng).CurrentRegion

 oRng.CopyPicture xlScreen, xlPicture
 lWidth = oRng.Width
 lHeight = oRng.Height

 Set oChrtO = oWs.ChartObjects.Add(Left:=0, Top:=0, Width:=lWidth, Height:=lHeight)

 oChrtO.Activate
 With oChrtO.Chart
  .Paste
  .Export Filename:="C:\Users\allso\Desktop\new vba projects\temp" & num & ".jpg", Filtername:="JPG"
 End With

 oChrtO.Delete

 'shows alerts
    Application.DisplayAlerts = True
End Sub

Sub callingfunc()
Workbooks.Open "C:\Users\allso\Desktop\new vba projects\new project subham brother\DPR NOV 2020.xlsb"
Dim ws As Worksheet
Set ws = Workbooks("DPR NOV 2020.xlsb").sheets("AREA")
Call Exportrangetopicture(ws, "J2", 1)
Set ws = Nothing
Set ws = Workbooks("DPR NOV 2020.xlsb").sheets("Zone")
Call Exportrangetopicture(ws, "H1", 2)
Workbooks("DPR NOV 2020.xlsb").Close SaveChanges:=True
End Sub

Change the range of source data of a pivot table programmatically using VBA

 
Option Explicit

Sub Copy_Paste_To_DPR_Pivot()
'Find the last used row in both sheets and copy and paste data below existing data.

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lcopyLastRow As Long
Dim lDestLastRow As Long

'Open method requires full file path to be referenced.

Workbooks.Open "C:\Users\allso\Desktop\new vba projects\new project subham brother\DPR NOV 2020.xlsb"

  'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("New Raw File Dual@.xlsb").Worksheets("NEW")
  Set wsDest = Workbooks("DPR NOV 2020.xlsb").Worksheets("RAW FILE")
    
 
 
  'clear content on the destination sheet except header
 
  wsDest.Rows("2:" & wsDest.Rows.Count).ClearContents
 
   '1. Find last used row in the copy range based on data in column A
  lcopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
 
 
  'Copy range to clipboard
  wsCopy.range("A2:P" & lcopyLastRow).Copy
 
  'PasteSpecial to paste values, formulas, formats, etc.
  wsDest.range("A2").PasteSpecial Paste:=xlPasteValues
    
    'arrange and refresh the pivot table
    
    'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("DPR NOV 2020.xlsb").Worksheets("RAW FILE")
  Set wsDest = Workbooks("DPR NOV 2020.xlsb").Worksheets("PIVOT")
  lcopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
  Dim datarange As String
 
   datarange = wsCopy.Name & "!" & range("A1:P" & lcopyLastRow).Address(ReferenceStyle:=xlR1C1)
   
   
   


        
        wsDest.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
        PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        datarange)
 
 
 

  'Close the workbook

  Workbooks("DPR NOV 2020.xlsb").Close SaveChanges:=True
 
End Sub




Wednesday, September 23, 2020

AutomatingTranslation of text as well as numbers in worksheet cells from one language to other using internet explorer and vba

Option Explicit

Function GetNumeric(CellRef As String)
Dim StringLength As Integer, i As Integer, result As String


StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then result = result & Mid(CellRef, i, 1)
Next i
GetNumeric = result
End Function


Sub test()
Sheets("Sheet2").Select
Range("A1").Select
'MsgBox (GetNumeric(ActiveCell.Value))
While ActiveCell.Value <> ""


ActiveCell.Offset(0, 1).Value = Replace(ActiveCell.Value, GetNumeric(ActiveCell.Value), LCase(NumToWords(GetNumeric(ActiveCell.Value))))
ActiveCell.Offset(0, 2).Value = translate_using_vba(ActiveCell.Offset(0, 1).Value, "bn")
ActiveCell.Offset(1, 0).Select
Wend

ActiveSheet.Cells.Columns.AutoFit

End Sub



      
'Main Function
Function NumToWords(ByVal MyNumber)
    
    'Written by Philip Treacy
    'http://www.myonlinetraininghub.com/convert-numbers-currency-to-words-with-excel-vba
    'Feb 2014
    'Based on code from Microsoft http://support.microsoft.com/kb/213360
    'This code is not guaranteed to be error free.  No warranty is implied or expressed. Use at your own risk and carry out your own testing
    
    Dim Units As String
    Dim SubUnits As String
    Dim TempStr As String
    Dim DecimalPlace As Integer
    Dim Count As Integer
    Dim DecimalSeparator As String
    Dim UnitName As String
    Dim SubUnitName As String
    Dim SubUnitSingularName As String
    
    DecimalSeparator = "."
    
    ReDim Place(9) As String
    Place(2) = " Thousand "
    Place(3) = " Million "
    Place(4) = " Billion "
    Place(5) = " Trillion "
            
    ' Convert MyNumber to STRING and TRIM white space
    MyNumber = Trim(CStr(MyNumber))
        
    'If MyNumber is blank then exit
    If MyNumber = "" Then
    
        NumToWords = ""
        
        Exit Function
    
    End If
        
    ' Find Position of decimal place, 0 if none.
    DecimalPlace = InStr(MyNumber, DecimalSeparator)
    
    
    ' Convert SubUnits and set MyNumber to Units amount.
    If DecimalPlace > 0 Then
    
        SubUnits = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & "00", 2))
        MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
        
    End If
    
    
    Count = 1
    Do While MyNumber <> ""
        
        TempStr = GetHundreds(Right(MyNumber, 3))
        
        If TempStr <> "" Then Units = TempStr & Place(Count) & Units
        
        If Len(MyNumber) > 3 Then
        
            MyNumber = Left(MyNumber, Len(MyNumber) - 3)
            
        Else
            
            MyNumber = ""
            
        End If
        
        Count = Count + 1
        
    Loop
    
    NumToWords = Application.Trim(Units)
    
End Function
      
      
' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
    
    Dim result As String
    
    If Val(MyNumber) = 0 Then Exit Function
    
    MyNumber = Right("000" & MyNumber, 3)
    
    ' Convert the hundreds place.
    If Mid(MyNumber, 1, 1) <> "0" Then
        
        result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
           
    End If
    
           
    ' Convert the tens and ones place.
    If Mid(MyNumber, 2, 1) <> "0" Then
        
        result = result & GetTens(Mid(MyNumber, 2))
        
    Else
    
        result = result & GetDigit(Mid(MyNumber, 3))
        
    End If
    
    GetHundreds = result
    
End Function
      
' Converts a number from 10 to 99 into text.
Function GetTens(TensText)

    Dim result As String
    
    result = ""           ' Null out the temporary function value.
    
    If Val(Left(TensText, 1)) = 1 Then   ' If value between 10-19...
        
        Select Case Val(TensText)
            
            Case 10: result = "Ten"
            Case 11: result = "Eleven"
            Case 12: result = "Twelve"
            Case 13: result = "Thirteen"
            Case 14: result = "Fourteen"
            Case 15: result = "Fifteen"
            Case 16: result = "Sixteen"
            Case 17: result = "Seventeen"
            Case 18: result = "Eighteen"
            Case 19: result = "Nineteen"
            Case Else
        
        End Select
        
    Else                                 ' If value between 20-99...
        
        Select Case Val(Left(TensText, 1))
            
            Case 2: result = "Twenty "
            Case 3: result = "Thirty "
            Case 4: result = "Forty "
            Case 5: result = "Fifty "
            Case 6: result = "Sixty "
            Case 7: result = "Seventy "
            Case 8: result = "Eighty "
            Case 9: result = "Ninety "
            Case Else
        
        End Select
        
        result = result & GetDigit(Right(TensText, 1))   ' Retrieve ones place.
        
    End If
    
    GetTens = result
    
End Function
     
' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)

    Select Case Val(Digit)
    
        Case 1: GetDigit = "One"
        Case 2: GetDigit = "Two"
        Case 3: GetDigit = "Three"
        Case 4: GetDigit = "Four"
        Case 5: GetDigit = "Five"
        Case 6: GetDigit = "Six"
        Case 7: GetDigit = "Seven"
        Case 8: GetDigit = "Eight"
        Case 9: GetDigit = "Nine"
        Case Else: GetDigit = ""
        
    End Select
    
End Function
Function translate_using_vba(str, langchoice) As String
' Tools Refrence Select Microsoft internet Control


    Dim IE As Object, i As Long
    Dim inputstring As String, outputstring As String, text_to_convert As String, result_data As String
    Dim CLEAN_DATA
    
    
    
    
    
    

    Set IE = CreateObject("InternetExplorer.application")
    '   TO CHOOSE INPUT LANGUAGE

    inputstring = "auto"

    '   TO CHOOSE OUTPUT LANGUAGE

    outputstring = langchoice

    text_to_convert = str

    'open website

    IE.Visible = False
    
    
    
    
    IE.navigate "http://translate.google.com/#" & inputstring & "/" & outputstring & "/" & text_to_convert

    Do Until IE.ReadyState = 4
        DoEvents
    Loop

    Application.Wait (Now + TimeValue("0:00:10"))
Do Until IE.ReadyState = 4
        DoEvents
    Loop
    
    IE.Quit
    translate_using_vba = IE.Document.getElementsByclassname("tlid-translation translation")(0).outertext
    



    

End Function


Monday, September 21, 2020

Adding a reference ,using it and remove the reference at the end programmatically using VBA

 

 

 

Most common Office GUID:

Microsoft Excel  {00020813-0000-0000-C000-000000000046}
Microsoft Word  {00020905-0000-0000-C000-000000000046}
Microsoft PowerPoint  {91493440-5A91-11CF-8700-00AA0060263B}
Microsoft Access  {4AFFC9A0-5F99-101B-AF4E-00AA003F0F07}
Microsoft Outlook {00062FFF-0000-0000-C000-000000000046}

 

 

 

 

 

 

 

' ----------------------------------------------------------------
' Purpose: Add Microsoft Outlook Object Library, call a procedure using that library, then remove Outlook Object Library
' ----------------------------------------------------------------
Sub callingProcedureMSOutlookObjLibrary()

    Dim strGUID As String

    'Microsoft Outlook GUID
    strGUID = "{00062FFF-0000-0000-C000-000000000046}"

    'Check if reference is already added to the project, if not add it
    If F_isReferenceAdded(strGUID) = False Then
        ThisWorkbook.VBProject.REFERENCES.AddFromGuid strGUID, 0, 0
    End If
    
    'Calling the procedure using Outlook object library
    Call procedureUsingMSOutlookObjectLibrary
    
    'Check if reference is added to the project, if yes remove
    If F_isReferenceAdded(strGUID) = True Then
        ThisWorkbook.VBProject.REFERENCES.Remove F_idReferenceByGUID(strGUID)
    End If
    
End Sub
' ----------------------------------------------------------------
' Purpose: Create new Outlook document with early binding, add two paragraphs, align the 2nd one to center
' ----------------------------------------------------------------

'sending mail with pdf attachments


Sub procedureUsingMSOutlookObjectLibrary()


Dim olapp As Outlook.Application
Dim olemail As Outlook.MailItem
Dim objFSO As Object
Dim objFldr As Object
Dim objFile  As Object
Dim strfullpath As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFldr = objFSO.GetFolder(Environ("UserProfile") & "\Desktop\excel_to_pdf_2")

Set olapp = New Outlook.Application
Set olemail = olapp.CreateItem(olMailItem)

With olemail

.BodyFormat = olFormatHTML

.Display
.HTMLBody = "Dear Someone" & "<br>" & .HTMLBody
'.Attachments.Add Environ("UserProfile") & "\Desktop\excel_to_pdf_2\Financial Sample.Canada.20200920_022807.pdf"
For Each objFile In objFldr.Files
        strfullpath = objFldr.Path & "\" & objFile.Name

        If LCase(Trim(objFSO.GetExtensionName(strfullpath))) = "pdf" Then
        'MsgBox strfullpath
            'SendasAttachment (strfullpath)
          .Attachments.Add strfullpath
        End If
    Next

.To = "allsourav2@gmail.com"
.Subject = "Test using VBA"
.Send




End With
Set olapp = Nothing
Set olemail = Nothing
End Sub

' ----------------------------------------------------------------
' Purpose: Check if an Object Library refernce is added to a VBAProject or not
' ----------------------------------------------------------------
Function F_isReferenceAdded(referenceGUID As String) As Boolean

    Dim varRef As Variant

    'Loop through VBProject references if input GUID found return TRUE otherwise FALSE
    For Each varRef In ThisWorkbook.VBProject.REFERENCES
        
        If varRef.GUID = referenceGUID Then
            F_isReferenceAdded = True
            Exit For
        End If
        
    Next varRef

End Function
' ----------------------------------------------------------------
' Purpose: Return Object Library reference as object, found by its GUID
' ----------------------------------------------------------------
Function F_idReferenceByGUID(referenceGUID As String) As Object

    Dim varRef As Object

    For Each varRef In ThisWorkbook.VBProject.REFERENCES
        
        If varRef.GUID = referenceGUID Then
            Set F_idReferenceByGUID = varRef
            Exit For
        End If
        
    Next varRef

End Function

Source:https://www.excelcise.org/add-or-remove-object-library-reference-via-vba/

Monday, May 4, 2020

Get unique values from an array and store them in another dynamically expanding array in VBA ,VBA Teacher Sourav,Kolkata 8910141720

Option Explicit

Sub uniquearray()
Dim arrdata() As String
Dim workingrange, cell As Range
Dim length As Integer
length = 0
Sheets("conditionalformattingvba").Select
Set workingrange = Range("I2").CurrentRegion
For Each cell In workingrange
length = length + 1
ReDim Preserve arrdata(length) As String
arrdata(length) = cell.Value

Next cell

'For length = 1 To UBound(arrdata)
'Debug.Print (arrdata(length))
'Next length

'MsgBox (arrdata(0))
Dim uniquearray() As String

Dim i As Integer


ReDim uniquearray(1) As String
For length = 1 To UBound(arrdata)
For i = 1 To UBound(uniquearray)

'Debug.Print tempstr1 & " and " & tempstr2
If arrdata(length) = uniquearray(i) Then

Exit For
End If




Next i
If i > UBound(uniquearray) Then
uniquearray(UBound(uniquearray)) = arrdata(length)
ReDim Preserve uniquearray(UBound(uniquearray) + 1) As String

End If


Next length
ReDim Preserve uniquearray(UBound(uniquearray) - 1) As String
For length = 1 To UBound(uniquearray)
Debug.Print (uniquearray(length))
Next length




End Sub

Sunday, May 3, 2020

Dictionary in VBA using example

Option Explicit

Sub dictionaryexample()

Sheets("conditionalformattingvba").Select
Dim dict As Object 'Declare a generic Object reference
Set dict = CreateObject("Scripting.Dictionary") 'Late Binding of the Dictionary
Range("T2").Select
While ActiveCell.Value <> ""
Dim key, val
key = ActiveCell.Value: val = ActiveCell.Offset(0, 1).Address
'Add item to VBA Dictionary
If Not dict.Exists(key) Then
    dict.Add key, val
End If
ActiveCell.Offset(1, 0).Select


Wend

Debug.Print dict.Count 'Result: 1

For Each key In dict.Keys
   Debug.Print key
Next key

'Print all items
For Each val In dict.Items
   Debug.Print val
Next val


'copy format of cells to different location
Dim tempaddress As String
Range("V2").Select
tempaddress = Selection.Address
For Each val In dict.Items

Range(val).Select
Selection.Copy
Range(tempaddress).PasteSpecial Paste:=xlPasteFormats
tempaddress = ActiveCell.Offset(1, 0).Address

Next val
Application.CutCopyMode = False


'Dispose of VBA Dictionary
Set dict = Nothing
End Sub

Conditional formatting using VBA where the conditions and the respective formatting is given,VBA Teacher Kolkata,Sourav Bhattacharya








If you zoom in the picture on the right side there are conditions and the formatting 

after running the macro the formatting based on the given conditions will be applied on the data 


The source code :


Option Explicit

Sub conditionsuperfinal()
Sheets("conditionalformattingvba").Select
Dim dict As Object 'Declare a generic Object reference
Set dict = CreateObject("Scripting.Dictionary") 'Late Binding of the Dictionary
Range("T2").Select
While ActiveCell.Value <> ""
Dim key, val
key = ActiveCell.Value: val = ActiveCell.Offset(0, 1).Address
'Add item to VBA Dictionary
If Not dict.Exists(key) Then
    dict.Add key, val
End If
ActiveCell.Offset(1, 0).Select


Wend

'Debug.Print dict.Count 'Result: 1
'
'For Each key In dict.Keys
'   Debug.Print key
'Next key
'
''Print all items
'For Each val In dict.Items
'   Debug.Print val
'Next val


'copy format of cells where condition matches
'Dim tempaddress As String
'Range("V2").Select
'tempaddress = Selection.Address
'For Each val In dict.Items
'
'Range(val).Select
'Selection.Copy
'Range(tempaddress).PasteSpecial Paste:=xlPasteFormats
'tempaddress = ActiveCell.Offset(1, 0).Address
'
'Next val
'Application.CutCopyMode = False

Sheets("conditionalformattingvba").Select
Dim workingrange, cell As Range
Range("I2:N19").Select
Set workingrange = Selection

For Each cell In workingrange
For Each key In dict.Keys
If InStr(1, cell.Value, key, vbTextCompare) > 0 Then
Range(dict(key)).Select
Selection.Copy
cell.PasteSpecial Paste:=xlPasteFormats
Exit For

Else
cell.ClearFormats
End If
Next key

Next cell


'Dispose of VBA Dictionary
Set dict = Nothing


End Sub

Sunday, April 12, 2020

Using Excel formulas with and without RC notation in VBA,VBA Teacher Sourav,Kolkata 08910141720

 Without RC notation

Sub usingexcelfunctioninvba()

Sheets("prg").Select
Dim workingrange As Range


Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Set workingrange = Selection
Dim sumresult As Integer
sumresult = Application.sum(workingrange)
Dim average As Double
average = Application.average(workingrange)
Dim count As Integer
count = Application.count(workingrange)
Dim max, min As Double
max = Application.max(workingrange)
min = Application.min(workingrange)
Dim stdevsample As Double
stdevsample = Application.WorksheetFunction.StDev_S(workingrange)
Dim stdevpopulation As Double
stdevpopulation = Application.WorksheetFunction.StDev_P(workingrange)
Dim median, mean, mode As Double
median = Application.WorksheetFunction.median(workingrange)
'mean = Application.WorksheetFunction.mean(workingrange)
mode = Application.mode(workingrange)
Range("A5").Value = sumresult
Range("B5").Value = average
Range("C5").Value = count
Range("D5").Value = max
Range("E5").Value = min
Range("F5").Value = stdevsample
Range("G5").Value = stdevpopulation
Range("H5").Value = average
Range("I5").Value = median
Range("J5").Value = mode

End Sub



With RC notation

Option Explicit

Sub usingrcformulainvba()
Sheets("prg").Select
Range("A1").Select
Dim firstrangerow As Integer
firstrangerow = (ActiveCell.Row)
Dim firstrangecolumn As Integer
firstrangecolumn = (ActiveCell.Column)
Selection.End(xlToRight).Select
Dim lastrangerow As Integer
lastrangerow = (ActiveCell.Row)
Dim lastrangecolumn As Integer
lastrangecolumn = (ActiveCell.Column)

Range("A7").Select

Dim currentrangerow As Integer
currentrangerow = (ActiveCell.Row)
Dim currentrangecolumn As Integer
currentrangecolumn = (ActiveCell.Column)

'MsgBox (firstrangerow - currentrangerow)


ActiveCell.FormulaR1C1 = "=SUM(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"
ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=Average(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=count(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=max(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=min(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=stdev.s(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=stdev.p(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=average(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"

ActiveCell.Offset(0, 1).Select

currentrangerow = (ActiveCell.Row)

currentrangecolumn = (ActiveCell.Column)
ActiveCell.FormulaR1C1 = "=median(R[" & (firstrangerow - currentrangerow) & "]C[" & (firstrangecolumn - currentrangecolumn) & "]:R[" & (lastrangerow - currentrangerow) & "]C[" & (lastrangecolumn - currentrangecolumn) & "])"
End Sub

Sunday, March 15, 2020

Filter a dynamic range with multiple criteria and save each filtered result in predefined sheet using VBA,VBA Teacher Sourav,Kolkata 08910141720


Function RemoveDupesColl(MyArray As Variant) As Variant
'DESCRIPTION: Removes duplicates from your array using the collection method.
'NOTES: (1) This function returns unique elements in your array, but
' it converts your array elements to strings.

'-----------------------------------------------------------------------
    Dim i As Long
    Dim arrColl As New Collection
    Dim arrDummy() As Variant
    Dim arrDummy1() As Variant
    Dim item As Variant
    ReDim arrDummy1(LBound(MyArray) To UBound(MyArray))

    For i = LBound(MyArray) To UBound(MyArray) 'convert to string
        arrDummy1(i) = CStr(MyArray(i))
    Next i
    On Error Resume Next
    For Each item In arrDummy1
       arrColl.Add item, item
    Next item
    Err.Clear
    ReDim arrDummy(LBound(MyArray) To arrColl.Count + LBound(MyArray) - 1)
    i = LBound(MyArray)
    For Each item In arrColl
       arrDummy(i) = item
       i = i + 1
    Next item
    RemoveDupesColl = arrDummy
End Function


Sub filterandpastedata()


Sheets("Sheet2").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    On Error Resume Next
    ActiveSheet.ShowAllData
End If


Dim uniquedata()
Dim samplerange As Range

 Set samplerange = ActiveSheet.Range("E2", ActiveSheet.Range("E2").End(xlDown))
'MsgBox (samplerange.Rows.Count)
ReDim Preserve uniquedata(samplerange.Rows.Count)
Dim dict As Object
Dim length As Long
length = 0
Range("E2").Select
While ActiveCell.Value <> ""

uniquedata(length) = ActiveCell.Value
length = length + 1
ActiveCell.Offset(1, 0).Select
Wend

'For length = LBound(uniquedata) To UBound(uniquedata) - 1
'MsgBox (uniquedata(length))
'Next length
Dim uniquedatafinal()
uniquedatafinal = RemoveDupesColl(uniquedata)
'For length = LBound(uniquedatafinal) To UBound(uniquedatafinal) - 1
'MsgBox (uniquedatafinal(length))
'Next length


'now we found the unique names ,let us first delete anysheet containing such unique names and create sheets containing those names
Dim tempsheetname As String
 With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
   
  For length = LBound(uniquedatafinal) To UBound(uniquedatafinal) - 1
tempsheetname = (uniquedatafinal(length))

For Each wks In Application.Worksheets
        If wks.Name = tempsheetname Then wks.Delete
    Next

Next length

 For length = LBound(uniquedatafinal) To UBound(uniquedatafinal) - 1
     cntsheets = Application.Sheets.Count
    Set NewSheet = Application.Worksheets.Add(After:=Worksheets(cntsheets))
    NewSheet.Name = uniquedatafinal(length)
    Next length
   
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With

'Now creating sheets is done ,let us go back the data sheet and remove any filter from the sheet

Sheets("Sheet2").Select



Dim dataforfilter As String


For length = LBound(uniquedatafinal) To UBound(uniquedatafinal) - 1
dataforfilter = Replace(ActiveSheet.Range("E1").CurrentRegion.Address, "$", "")
ActiveSheet.Range(dataforfilter).AutoFilter Field:=1, Criteria1:=uniquedatafinal(length), Operator:=xlFilterValues
ActiveSheet.Range(dataforfilter).AutoFilter Field:=4, Criteria1:="=Yes", Operator:=xlFilterValues

ActiveSheet.Range("E1").CurrentRegion.Select
Selection.Copy

Sheets(uniquedatafinal(length)).Select
Range("A1").PasteSpecial xlPasteValues

Sheets("Sheet2").Select
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    On Error Resume Next
    ActiveSheet.ShowAllData
End If

Next length

If ActiveSheet.AutoFilterMode Then

     ActiveSheet.AutoFilterMode = False

End If

End Sub


Monday, March 9, 2020

Connect and get data from microsoft access database in excel using vba

Option Explicit

Sub ExportDataToAccess()

    Dim ConnObj As ADODB.Connection
    Dim RecSet As ADODB.Recordset
    Dim ConnCmd As ADODB.Command
    Dim ColNames As ADODB.Fields
    Dim DataSource As String
    Dim intLoop As Integer
   
    'Define the data source
    DataSource = "C:\Users\sourav\Desktop\A732CreatingForms_1.accdb"

    'Create a new connection object & a new command object
    Set ConnObj = New ADODB.Connection
    Set ConnCmd = New ADODB.Command

    'Create a new connection
    With ConnObj
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = DataSource
        .Open
    End With
   
    'This will allow the command object to use the Active Connection
    ConnCmd.ActiveConnection = ConnObj

    'Define the Query String & the Query Type.
    ConnCmd.CommandText = "SELECT * from Employees;"
    ConnCmd.CommandType = adCmdText

    'Exectue the Query & Get the column Names.
    Set RecSet = ConnCmd.Execute
    Set ColNames = RecSet.Fields
   
    'Populate the header row of the Excel Sheet.
    For intLoop = 0 To ColNames.Count - 1
        Cells(1, intLoop + 1).Value = ColNames.Item(intLoop).Name
    Next
   
    'Dump the data in the worksheet.
    Range("A2").CopyFromRecordset RecSet
   
    'Close the Connection
    ConnObj.Close

End Sub

Copy excel data to another workbook using vba,VBA Teacher Sourav,Kolkata 08910141720

Sub copydatatoanotherworkbook()
'first we need to copy the data
Sheets("Firstvbasheet").Select
Range("H1:J14").Select
Selection.Copy


Workbooks.Add
ActiveSheet.Paste Destination:=Range("A1")
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Users\sourav\Desktop\temp.xlsx"
ActiveWorkbook.Close

Application.DisplayAlerts = True

End Sub

Saturday, February 8, 2020

Automating Pivot Table using VBA,VBA Teacher Sourav,Kolkata 08910141720

Sub pivotvba()
 With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
    End With
For Each wks In Application.Worksheets
        If wks.Name = "Pivot_Table" Then wks.Delete
    Next

 cntsheets = Application.Sheets.Count
    Set NewSheet = Application.Worksheets.Add(After:=Worksheets(cntsheets))
    NewSheet.Name = "Pivot_Table"
   
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
    End With
 Application.DisplayAlerts = True
  Dim pt As PivotTable
  Dim pc As PivotCache
  Dim pf As PivotField
  Dim pi As PivotItem

'set the pivotcache
Sheets("Data").Select
Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Data").Range("A3").CurrentRegion)

'create the pivot table
Sheets("Pivot_Table").Select
Set pt = ActiveSheet.PivotTables.Add(pc, Range("A3"), "Pivot_Table_1")

'put the fields

With pt
'.PivotFields("Salesperson").Orientation = xlColumnField
.PivotFields("Category").Orientation = xlRowField
.PivotFields("Salesperson").Orientation = xlColumnField
.PivotFields("Revenue").Orientation = xlDataField
'set the number format

.DataBodyRange.NumberFormat = "$#,##0.00"

'classic view

.InGridDropZones = True


'switch back from classic view
.InGridDropZones = False

'add calculated field

.CalculatedFields.Add "Eligible for bonus", "= IF(Revenue >1500,1,0)", True
.PivotFields("Eligible for bonus").Orientation = xlDataField
'Changing the caption of the calculated field,removing the sum of part
.DataPivotField.PivotItems("Sum of Eligible for bonus").Caption = "Eligible for bonus ? "

'changing the number format of the callculated field so that it becomes only 1 and 0

.PivotFields("Eligible for bonus ? ").NumberFormat = "#,##0"
'converting 1 and 0 to yes and no

.PivotFields("Eligible for bonus ? ").NumberFormat = """Yes"";;""No"""

'Add region column as report filter
.PivotFields("Region").Orientation = xlPageField


End With
'Setting default filter

Set pf = pt.PivotFields("Region")
With pf
   For Each pi In pf.PivotItems
   If pi.Name = "East" Then
   pi.Visible = True
   Else
   pi.Visible = False
   End If
  
   Next pi
 End With

'setting filter in a more customized way,suppose
'we want to see revenue generated by eastern region with
'the category beverages,we already filtered the data by east
'now let us filter the filtered table by a cirtain category

Set pf = pt.PivotFields("Category")
With pf
   For Each pi In pf.PivotItems
   If pi.Name = "Beverages" Then
   pi.Visible = True
   Else
   pi.Visible = False
   End If
  
   Next pi
 End With

'Suppose we want to filter column by both east and west

Set pf = pt.PivotFields("Region")
With pf
   For Each pi In pf.PivotItems
   If pi.Name = "East" Or pi.Name = "West" Then
   pi.Visible = True
   Else
   pi.Visible = False
   End If
  
   Next pi
 End With
'Suppose we want to filter the row by both beverages and candy
Set pf = pt.PivotFields("Category")
With pf
   For Each pi In pf.PivotItems
   If pi.Name = "Beverages" Or pi.Name = "Candy" Then
   pi.Visible = True
   Else
   pi.Visible = False
   End If
  
   Next pi
 End With

'Update the pivot table

ThisWorkbook.RefreshAll
End Sub

Wednesday, February 5, 2020

Arrays in VBA

Sub DeclaringArrays()
'Declare Array with range 0,1,2,3
Dim MyArray(0 To 3) As Variant
'Declare Array with range 0,1,2,3
Dim MyArray(3) As Variant
'Declare Array with range 1,2,3
Dim MyArray(1 To 3) As Variant
'Declare Array with range 2,3,4
Dim MyArray(2 To 4) As Variant
'DYNAMIC ARRAYS
'Declare Array with Dynamic Range
Dim MyArray() As Variant
'Resize Array with range 0,1,2,3,4
ReDim MyArray(0 To 4)
'ASSIGN VALUES TO AN ARRAY
MyArray(0) = 100
MyArray(1) = 200
MyArray(2) = 300
MyArray(3) = 400
MyArray(4) = 500
MyArray(5) = 600 '<<< Will Return an error because there is not 5th element.
'LOOP THROUGH ARRAYS
'Using For Loop
Dim i As Long
For i = LBound(MyArray) To UBound(MyArray)
Debug.Print MyArray(i)
Next
'Using For Each Loop
Dim Elem As Variant
For Each Elem In MyArray
Debug.Print Elem
Next
'USE ERASE
'Declare Static Array
Dim MyArray(0 To 3) As Long
Erase MyArray '<<< All Values will be set to 0.
'Declare Dynamic Array
Dim MyArray() As Long
ReDim MyArray(0 To 3)
Erase MyArray '<<< Array is erased from memory.
'USE REDIM
Dim MyArray() As Variant
MyArray(0) = "MyFirstElement"
'Old Array with "MyFirstElement" is now deleted.
ReDim MyArray(0 To 4)
Dim MyArray() As Variant
MyArray(0) = "MyFirstElement"
'Old Array with "MyFirstElement" is now Resized With Original Content Kept in Place.
ReDim Preserve MyArray(0 To 4)
'USING MULTIDIMENSIONAL ARRAYS
'Declare two dimensional array
Dim MultiDimArray(0 To 3, 0 To 3) As Integer
Dim i, j As Integer
'Assign values to array
For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1)
For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2)
MultiDimArray(i, j) = i + j
Next j
Next i
'Print values from array.
For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1)
For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2)
Debug.Print MultiDimArray(i, j)
Next j
Next i
End Sub
Attribute VB_Name = "Arrays"