VBA to open 2 workbooks(name changes on 1), copy and paste data and drag down existing formula

cdalgorta

Board Regular
Joined
Jun 5, 2022
Messages
87
Office Version
  1. 365
Platform
  1. Windows
Hi,
Thank you in advance. This one is a bit long. Sorry!

So I download a file daily and I use that to replace the data on another file which is 1 of my database excels for my main template.
The VBA that I'd need would be the following:
* Open both Excels(I'm guessing they have to be opened for this to work).
The daily new data always goes to my "Downloads" file, the name always starts with "Additional info looker Standard Unlimited " followed by the date and then random characters(I delete the one from the previous day, so there will always only be 1 file in my downloads that starts with "Additional info looker Standard Unlimited ".
There is only 1 sheet on the workbook and the name is always "Additional info looker Standard".
1658079371265.png


I need to copy all columns from A to S. The number of rows always changes(could be more, could be less), but it's between 100k to 200k(if that matters). Also, not sure if this matters as well, but A1 is empty as you can see in the image.
1658076462105.png


*By the way, this daily download file is a .csv file.*

Now, the file I need to paste the data in, is here:
C:\Users\cristian\Desktop\Standard Aging Local
Name: Additional Info Lookup Data
Sheet name: Additional Info Lookup
1658076750843.png

There are formulas on columns T and U, so I was thinking that the best way to do it, would be with a VBA that deletes everything below Row 3, paste the data from the previous file into this one from A2 to S2 all the way down, and then drag the formulas on T2 and U2 all the way down until the last row of the new data. And that would finish what I need.
1658077449548.png


P.S. If possible, I think a VBA that turns "Calculation Options" to "Manual" before opening the 2nd file with the formulas, and then another one that triggers "Calculate Now" after dragging down the formulas on T2 and U2, would make this better. For some reason, "sometimes" when I open the workbook with the formulas, it starts recalculating the formulas even though I just opened it and nothing has changed. I have to remind myself to click "manual" before I open any excel with formulas or I have to wait for the thing to finish calculating... 😞

P.P.S If possible as well, a VBA to close the 1st file at the very end would be great. I know the VBA to close a file with a fixed name, but not when the file name changes and only part of the name is fixed, "Additional info looker Standard Unlimited ".

Thank you so much in advance! I'm thinking of paying for a Coursera VBA course so that I can start helping others here as well instead of just asking for help. Hahaha. There are quiet a few, so any recommendations from the experts would be greatly appreciate it!

Cristian
 
That should be fine, thank you for that.

We should have everything we need now.

I will respond back shortly, if nobody else responds sooner.
 
Upvote 0

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
I am up to testing the loading of the .csv and there appears to be a duplicate entry in one of the lines of data which is throwing off the data for that line.

6,1055023,7/15/2022,,Aldi,CM24755417,CM24755417,"SWN-182467,SWN-191216",Missing,,No,Spot,tendered,5176.04,0,90,0,"Columbia, MO","South Windsor, CT"

Edit:
Disregard that. There appears to be some combining of data I need to account for
 
Upvote 0
P.S. If possible, I think a VBA that turns "Calculation Options" to "Manual" before opening the 2nd file with the formulas, and then another one that triggers "Calculate Now" after dragging down the formulas on T2 and U2, would make this better. For some reason, "sometimes" when I open the workbook with the formulas, it starts recalculating the formulas even though I just opened it and nothing has changed. I have to remind myself to click "manual" before I open any excel with formulas or I have to wait for the thing to finish calculating... 😞

Ok I am back on the job now and I am wrapping up the code.

Do you have to keep the formulas in Columns T:U? A simple way around your issue that you have presented is just to remove the formulas and leave the values that the formulas resulted in.
 
Upvote 0
Ok I am back on the job now and I am wrapping up the code.

Do you have to keep the formulas in Columns T:U? A simple way around your issue that you have presented is just to remove the formulas and leave the values that the formulas resulted in.
If the VBA will add the same values the formula would, then that would be great. I don't need specifically the formula to be there, just the result. I usually only leave the formula on T2 and U2 so I don't have to type them again and just convert everything below into value(Excel takes about a minute to save sometimes when I leave the formulas). If it's simpler, then by all means, please go ahead. Thank you Johnny!
 
Upvote 0
Let me give a step by step on how to use the following two sets of codes:

1) Start with a new excel workbook.
2) Press Alt+F11 to open the VB Editor
3) Press Alt+I and then select 'Module' from the window that pops up
4) In the big window that pops up paste the following code:

VBA Code:
Sub CreateAClickableMacroButton()
'
    Dim ButtonHeighth                       As Long, ButtonLength                           As Long
    Dim ButtonTitle                         As String
    Dim CellToPutButtonInto                 As String
    Dim CodeNameOfSheetToPutClickableButton As String
    Dim LeftAddress                         As String, TopAddress                           As String
    Dim MacroToRunWhenButtonIsClicked       As String
    Dim NameOfSheetToPutClickableButton     As String, NameOfMacroToRunWhenButtonIsClicked  As String
'
    CellToPutButtonInto = "A1"                                              ' <--- Set this to the cell that you want the clickable button to be put into
    ButtonTitle = "Import CSV"                                              ' <--- Set this to what you want displayed on the button
    NameOfSheetToPutClickableButton = "Sheet1"                              ' <--- Set this sheet name to the desired sheet to put the clickable button into
    NameOfMacroToRunWhenButtonIsClicked = "LoadCSV_FileToSheet"             ' <--- Set this to the name of the subroutine that you want to run when button is clicked
'
    CodeNameOfSheetToPutClickableButton = Sheets(NameOfSheetToPutClickableButton).CodeName  ' Find the CodeName of the SheetName
    MacroToRunWhenButtonIsClicked = CodeNameOfSheetToPutClickableButton & "." & NameOfMacroToRunWhenButtonIsClicked
'
    ButtonHeighth = 15                                                      ' <--- Set this to the Default Height of button
    ButtonLength = Round(Len(ButtonTitle) * 8 * 0.98)                       ' Calculated value to set the ButtonLength to
'
    With Sheets(NameOfSheetToPutClickableButton)
        With .Buttons.Add(1, 1, ButtonLength, ButtonHeighth)
            .Top = .Parent.Range(CellToPutButtonInto).Top
            .Left = .Parent.Range(CellToPutButtonInto).Left
            .Caption = ButtonTitle                                          ' Title of clickable button
            .OnAction = MacroToRunWhenButtonIsClicked                       ' Subroutine to run when button is clicked
        End With
    End With
End Sub

5) Make any adjustments that you want to make to that code
6) Press Alt+F4 to return to Excel sheet
7) Right click the sheet tab at the bottom of the excel sheet that you elected to place the Button into.
8) select the 'View Code' from the window that pops up.
9) In the big window that pops up, paste the following code:

VBA Code:
Sub LoadCSV_FileToSheet()
'
    Dim StartTime                       As Double
    StartTime = Timer                                                                           ' Start the stopwatch
'
    Dim CSV_Column                      As Long, CSV_FileRow                As Long
    Dim FreeFileNumber                  As Long
    Dim ColumnNumber                    As Long, RowNumber                  As Long
    Dim StartRow                        As Long
    Dim CSV_FileToOpen                  As String, DestinationFile          As String, DestinationPath              As String
    Dim All_CSV_RowsFromCSV_FileArray   As Variant, CSV_FileRowColumnsArray As Variant, Partitioned_CSV_FileArray   As Variant
    Dim HeadersToAddArray               As Variant
    Dim wbDestination                   As Workbook
    Dim wsDestination                   As Worksheet
'
    DestinationPath = Environ("USERPROFILE") & "\Desktop\" & "Standard Aging Local\"            ' <--- Set this to the path of the DestinationFile
    DestinationFile = DestinationPath & "Additional Info Lookup Data.xlsx"                      ' <--- Set this to the name of the DestinationFile
'
    Set wbDestination = Workbooks.Open(DestinationFile)                                         '
'
    Set wsDestination = Sheets("Additional Info Lookup")                                        ' <--- Set this to the sheet name to dump the
'                                                                                               '       Partitioned_CSV_FileArray to
    StartRow = 2                                                                                ' <--- Set this to the start row of data

    HeadersToAddArray = Array("Stark Receivable Total", "Rounded Fuel Rate")                    ' <--- Set additional headers to add to T:U of wsDestination
'
    CSV_FileToOpen = Dir(Environ("USERPROFILE") & "\Downloads\" & _
            "Additional info looker Standard Unlimited*.csv")                                   ' Save found CSV file to CSV_FileToOpen
'
    FreeFileNumber = FreeFile                                                                   ' Get an unused file number
    Open Environ("USERPROFILE") & "\Downloads\" & CSV_FileToOpen For Input As #FreeFileNumber   ' Open the CSV file
'
    If Err.Number <> 0 Then                                                                     ' If error occurred then ...
        MsgBox "File open error #" & Err.Number & "!", vbCritical, "Error!"                     '   Display error #
        Exit Sub                                                                                '   Exit sub
    End If
'
    All_CSV_RowsFromCSV_FileArray = Split(Input(LOF(FreeFileNumber), #FreeFileNumber), vbCrLf)  ' Load all Rows in CSV file to All_CSV_RowsFromCSV_FileArray
    Close #FreeFileNumber                                                                       ' Close the CSV file
'
    RowNumber = 0                                                                               ' Initialize RowNumber
'
    ReDim Partitioned_CSV_FileArray(1 To UBound(All_CSV_RowsFromCSV_FileArray), 1 To 21)        ' Set rows/columns for Partitioned_CSV_FileArray
'
    For CSV_FileRow = LBound(All_CSV_RowsFromCSV_FileArray) To UBound(All_CSV_RowsFromCSV_FileArray)    ' Loop through all rows of CSV file
        If All_CSV_RowsFromCSV_FileArray(CSV_FileRow) <> vbNullString Then                      '   If CSV row is not blank then ...
            CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), ",")    '       Load contents of row to CSV_FileRowColumnsArray
'
            ColumnNumber = 1                                                                    '       Initialize ColumnNumber
            RowNumber = RowNumber + 1                                                           '       Increment RowNumber
'
            For CSV_Column = LBound(CSV_FileRowColumnsArray) To UBound(CSV_FileRowColumnsArray) '       Loop through columns
                If Left(CSV_FileRowColumnsArray(CSV_Column), 1) = Chr(34) Then                  '           If CSV_Column starts with a quote then ...
                    Partitioned_CSV_FileArray(RowNumber, ColumnNumber) = _
                        Replace(Trim(CSV_FileRowColumnsArray(CSV_Column)) & ", " & _
                        Trim(CSV_FileRowColumnsArray(CSV_Column + 1)), Chr(34), "")             '               Add values to Partitioned_CSV_FileArray
                    CSV_Column = CSV_Column + 1                                                 '               Increment CSV_Column
                Else                                                                            '           Else ...
                    Partitioned_CSV_FileArray(RowNumber, ColumnNumber) = _
                        CSV_FileRowColumnsArray(CSV_Column)                                     '               Add values to Partitioned_CSV_FileArray
                End If
'
                ColumnNumber = ColumnNumber + 1                                                 '           Increment ColumnNumber
            Next                                                                                '       Loop back
        End If
    Next                                                                                        ' Loop back
'
    Application.ScreenUpdating = False                                                          ' Turn ScreenUpdating off
'
    With wsDestination
        .UsedRange.Clear                                                                        '   Clear the previous rsults from destination sheet
        .Range("A1").Resize(UBound(Partitioned_CSV_FileArray, 1), _
                UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray         '   Display Partitioned_CSV_FileArray to sheet
        .Range("T1:U1").Value = HeadersToAddArray                                               '   Add headers to DestinationSheet
'
        .Range("T" & StartRow & ":T" & RowNumber).FormulaR1C1 = "=RC[-6]+RC[-4]+RC[1]+RC[-3]"   '   Load Formulas to Column T
        .Range("U" & StartRow & ":U" & RowNumber).FormulaR1C1 = "=ROUND(RC[-6],2)"              '   Load Formulas to Column U
'
        .Range("T" & StartRow & ":U" & RowNumber).Copy                                          '   Copy formula range into memory (Clipboard)
        .Range("T" & StartRow & ":U" & RowNumber).PasteSpecial xlPasteValues                    '   Paste just the values back to range
        Application.CutCopyMode = False                                                         '   Clear clipboard & 'marching ants' around copied range
'
        .UsedRange.EntireColumn.AutoFit                                                         '   Autofit used columns
    End With
'
    Application.ScreenUpdating = True                                                           ' Turn ScreenUpdating back on
'
    Debug.Print RowNumber & " Rows of data processed from the CSV file."                        ' Display the # of data lines that were processed
'                                                                                               '       to the 'Immediate Window'(CTRL-G)
    Debug.Print "Time to complete = " & Timer - StartTime & " seconds."                         ' Display the Time to complete CSV processing
'                                                                                               '       to the 'Immediate Window'(CTRL-G)
End Sub

10) Press Alt+F4 to return to Excel sheet
11) Press Alt+F8 and double click the 'CreateAClickableMacroButton' ' This will create the button on the sheet that you chose
12) Press F12 to 'Save As' & save the file as a 'xlsm' file
13) Close out the file and reopen it.
14) From then on you can click the button that was created and it will execute the code to open the CSV file location, etc.
 
Upvote 0
Let me give a step by step on how to use the following two sets of codes:

1) Start with a new excel workbook.
2) Press Alt+F11 to open the VB Editor
3) Press Alt+I and then select 'Module' from the window that pops up
4) In the big window that pops up paste the following code:

VBA Code:
Sub CreateAClickableMacroButton()
'
    Dim ButtonHeighth                       As Long, ButtonLength                           As Long
    Dim ButtonTitle                         As String
    Dim CellToPutButtonInto                 As String
    Dim CodeNameOfSheetToPutClickableButton As String
    Dim LeftAddress                         As String, TopAddress                           As String
    Dim MacroToRunWhenButtonIsClicked       As String
    Dim NameOfSheetToPutClickableButton     As String, NameOfMacroToRunWhenButtonIsClicked  As String
'
    CellToPutButtonInto = "A1"                                              ' <--- Set this to the cell that you want the clickable button to be put into
    ButtonTitle = "Import CSV"                                              ' <--- Set this to what you want displayed on the button
    NameOfSheetToPutClickableButton = "Sheet1"                              ' <--- Set this sheet name to the desired sheet to put the clickable button into
    NameOfMacroToRunWhenButtonIsClicked = "LoadCSV_FileToSheet"             ' <--- Set this to the name of the subroutine that you want to run when button is clicked
'
    CodeNameOfSheetToPutClickableButton = Sheets(NameOfSheetToPutClickableButton).CodeName  ' Find the CodeName of the SheetName
    MacroToRunWhenButtonIsClicked = CodeNameOfSheetToPutClickableButton & "." & NameOfMacroToRunWhenButtonIsClicked
'
    ButtonHeighth = 15                                                      ' <--- Set this to the Default Height of button
    ButtonLength = Round(Len(ButtonTitle) * 8 * 0.98)                       ' Calculated value to set the ButtonLength to
'
    With Sheets(NameOfSheetToPutClickableButton)
        With .Buttons.Add(1, 1, ButtonLength, ButtonHeighth)
            .Top = .Parent.Range(CellToPutButtonInto).Top
            .Left = .Parent.Range(CellToPutButtonInto).Left
            .Caption = ButtonTitle                                          ' Title of clickable button
            .OnAction = MacroToRunWhenButtonIsClicked                       ' Subroutine to run when button is clicked
        End With
    End With
End Sub

5) Make any adjustments that you want to make to that code
6) Press Alt+F4 to return to Excel sheet
7) Right click the sheet tab at the bottom of the excel sheet that you elected to place the Button into.
8) select the 'View Code' from the window that pops up.
9) In the big window that pops up, paste the following code:

VBA Code:
Sub LoadCSV_FileToSheet()
'
    Dim StartTime                       As Double
    StartTime = Timer                                                                           ' Start the stopwatch
'
    Dim CSV_Column                      As Long, CSV_FileRow                As Long
    Dim FreeFileNumber                  As Long
    Dim ColumnNumber                    As Long, RowNumber                  As Long
    Dim StartRow                        As Long
    Dim CSV_FileToOpen                  As String, DestinationFile          As String, DestinationPath              As String
    Dim All_CSV_RowsFromCSV_FileArray   As Variant, CSV_FileRowColumnsArray As Variant, Partitioned_CSV_FileArray   As Variant
    Dim HeadersToAddArray               As Variant
    Dim wbDestination                   As Workbook
    Dim wsDestination                   As Worksheet
'
    DestinationPath = Environ("USERPROFILE") & "\Desktop\" & "Standard Aging Local\"            ' <--- Set this to the path of the DestinationFile
    DestinationFile = DestinationPath & "Additional Info Lookup Data.xlsx"                      ' <--- Set this to the name of the DestinationFile
'
    Set wbDestination = Workbooks.Open(DestinationFile)                                         '
'
    Set wsDestination = Sheets("Additional Info Lookup")                                        ' <--- Set this to the sheet name to dump the
'                                                                                               '       Partitioned_CSV_FileArray to
    StartRow = 2                                                                                ' <--- Set this to the start row of data

    HeadersToAddArray = Array("Stark Receivable Total", "Rounded Fuel Rate")                    ' <--- Set additional headers to add to T:U of wsDestination
'
    CSV_FileToOpen = Dir(Environ("USERPROFILE") & "\Downloads\" & _
            "Additional info looker Standard Unlimited*.csv")                                   ' Save found CSV file to CSV_FileToOpen
'
    FreeFileNumber = FreeFile                                                                   ' Get an unused file number
    Open Environ("USERPROFILE") & "\Downloads\" & CSV_FileToOpen For Input As #FreeFileNumber   ' Open the CSV file
'
    If Err.Number <> 0 Then                                                                     ' If error occurred then ...
        MsgBox "File open error #" & Err.Number & "!", vbCritical, "Error!"                     '   Display error #
        Exit Sub                                                                                '   Exit sub
    End If
'
    All_CSV_RowsFromCSV_FileArray = Split(Input(LOF(FreeFileNumber), #FreeFileNumber), vbCrLf)  ' Load all Rows in CSV file to All_CSV_RowsFromCSV_FileArray
    Close #FreeFileNumber                                                                       ' Close the CSV file
'
    RowNumber = 0                                                                               ' Initialize RowNumber
'
    ReDim Partitioned_CSV_FileArray(1 To UBound(All_CSV_RowsFromCSV_FileArray), 1 To 21)        ' Set rows/columns for Partitioned_CSV_FileArray
'
    For CSV_FileRow = LBound(All_CSV_RowsFromCSV_FileArray) To UBound(All_CSV_RowsFromCSV_FileArray)    ' Loop through all rows of CSV file
        If All_CSV_RowsFromCSV_FileArray(CSV_FileRow) <> vbNullString Then                      '   If CSV row is not blank then ...
            CSV_FileRowColumnsArray = Split(All_CSV_RowsFromCSV_FileArray(CSV_FileRow), ",")    '       Load contents of row to CSV_FileRowColumnsArray
'
            ColumnNumber = 1                                                                    '       Initialize ColumnNumber
            RowNumber = RowNumber + 1                                                           '       Increment RowNumber
'
            For CSV_Column = LBound(CSV_FileRowColumnsArray) To UBound(CSV_FileRowColumnsArray) '       Loop through columns
                If Left(CSV_FileRowColumnsArray(CSV_Column), 1) = Chr(34) Then                  '           If CSV_Column starts with a quote then ...
                    Partitioned_CSV_FileArray(RowNumber, ColumnNumber) = _
                        Replace(Trim(CSV_FileRowColumnsArray(CSV_Column)) & ", " & _
                        Trim(CSV_FileRowColumnsArray(CSV_Column + 1)), Chr(34), "")             '               Add values to Partitioned_CSV_FileArray
                    CSV_Column = CSV_Column + 1                                                 '               Increment CSV_Column
                Else                                                                            '           Else ...
                    Partitioned_CSV_FileArray(RowNumber, ColumnNumber) = _
                        CSV_FileRowColumnsArray(CSV_Column)                                     '               Add values to Partitioned_CSV_FileArray
                End If
'
                ColumnNumber = ColumnNumber + 1                                                 '           Increment ColumnNumber
            Next                                                                                '       Loop back
        End If
    Next                                                                                        ' Loop back
'
    Application.ScreenUpdating = False                                                          ' Turn ScreenUpdating off
'
    With wsDestination
        .UsedRange.Clear                                                                        '   Clear the previous rsults from destination sheet
        .Range("A1").Resize(UBound(Partitioned_CSV_FileArray, 1), _
                UBound(Partitioned_CSV_FileArray, 2)).Value = Partitioned_CSV_FileArray         '   Display Partitioned_CSV_FileArray to sheet
        .Range("T1:U1").Value = HeadersToAddArray                                               '   Add headers to DestinationSheet
'
        .Range("T" & StartRow & ":T" & RowNumber).FormulaR1C1 = "=RC[-6]+RC[-4]+RC[1]+RC[-3]"   '   Load Formulas to Column T
        .Range("U" & StartRow & ":U" & RowNumber).FormulaR1C1 = "=ROUND(RC[-6],2)"              '   Load Formulas to Column U
'
        .Range("T" & StartRow & ":U" & RowNumber).Copy                                          '   Copy formula range into memory (Clipboard)
        .Range("T" & StartRow & ":U" & RowNumber).PasteSpecial xlPasteValues                    '   Paste just the values back to range
        Application.CutCopyMode = False                                                         '   Clear clipboard & 'marching ants' around copied range
'
        .UsedRange.EntireColumn.AutoFit                                                         '   Autofit used columns
    End With
'
    Application.ScreenUpdating = True                                                           ' Turn ScreenUpdating back on
'
    Debug.Print RowNumber & " Rows of data processed from the CSV file."                        ' Display the # of data lines that were processed
'                                                                                               '       to the 'Immediate Window'(CTRL-G)
    Debug.Print "Time to complete = " & Timer - StartTime & " seconds."                         ' Display the Time to complete CSV processing
'                                                                                               '       to the 'Immediate Window'(CTRL-G)
End Sub

10) Press Alt+F4 to return to Excel sheet
11) Press Alt+F8 and double click the 'CreateAClickableMacroButton' ' This will create the button on the sheet that you chose
12) Press F12 to 'Save As' & save the file as a 'xlsm' file
13) Close out the file and reopen it.
14) From then on you can click the button that was created and it will execute the code to open the CSV file location, etc.
Hi Johnny. It gave me this:
1658109188747.png


Edit: I didn't change anything btw. Copy/paste all.
 
Upvote 0
Your past couple of posts are not making sense.

Post #17 shows a display of the destination sheet. Post #19 shows that you are getting error when creating the button to click on.

Please follow the steps exactly as described in post #16 and then report back the result.
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,322
Members
452,635
Latest member
laura12345

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top