Loop through multiple files in folder and copy/paste to master file - excel

I need to copy from multiple files in a specific folder and paste into a Master file. All files have a sheet called "Analysis", variable rows, but constant columns. I need to copy from all files the sheet "Analysis" A4:AB and paste in workbook called "Evaluations" in Sheet called "Evaluations" G2:AH, one below the other. I have the below code, which worked but doesn't anymore and I don't know why. Can you please help?
Sub CopyRange()
Application.ScreenUpdating = False
Dim wkbDest As Workbook
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Dim lastRow As Long
Const strPath As String = "V:\Trade Marketing\Trade Finance\2021\Projects\Evaluation\Analysis\"
ChDir strPath
strExtension = Dir("*.xls*")
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath & strExtension)
With wkbSource
lastRow = .Sheets("Analysis").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
.Sheets("Analysis").Range("A4:AB" & lastRow).Copy wkbDest.Sheets("Evaluations").Cells(Rows.Count, "G").End(xlUp).Offset(1, 0)
.Close SaveChanges:=False
End With
strExtension = Dir
Loop
Application.ScreenUpdating = True
End Sub

Backup Data Columns
Option Explicit
Sub AnalysisBackup()
Const swbPath As String _
= "V:\Trade Marketing\Trade Finance\2021\Projects\Evaluation\Analysis\"
Const swbPattern As String = "*.xls*"
Const sName As String = "Analysis"
Const sCols As String = "A:AB"
Const sFirstRow As Long = 4
Const dName As String = "Evaluations"
Const dFirst As String = "G2"
Dim swbName As String: swbName = Dir(swbPath & swbPattern)
If swbName = "" Then Exit Sub ' no file found
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
Dim cCount As Long: cCount = dws.Columns(sCols).Columns.Count
Dim dirrg As Range: Set dirrg = dws.Range(dFirst).Resize(, cCount)
Dim drrg As Range ' Destination First Row Range
Dim dlCell As Range ' Destination Last Cell
Set dlCell = dirrg.Resize(dws.Rows.Count - dirrg.Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If dlCell Is Nothing Then
Set drrg = dirrg
Else
Set drrg = dirrg.Offset(dlCell.Row - dirrg.Row + 1)
End If
Dim swb As Workbook ' Source Workbook
Dim sws As Worksheet ' Source Worksheet
Dim srg As Range ' Source Range
Dim slCell As Range ' Source Last Cell
Dim srCount As Long ' Source Range Rows Count
Dim drg As Range ' Destination Range
Application.ScreenUpdating = False
Do While swbName <> ""
Set swb = Workbooks.Open(swbPath & swbName)
Set sws = Nothing
On Error Resume Next
Set sws = swb.Worksheets(sName)
On Error GoTo 0
If Not sws Is Nothing Then
Set slCell = Nothing
With sws.Rows(sFirstRow).Columns(sCols)
Set slCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If Not slCell Is Nothing Then
srCount = slCell.Row - .Row + 1
Set srg = .Resize(srCount)
Set drg = drrg.Resize(srCount)
drg.Value = srg.Value
Set drrg = drrg.Offset(srCount)
'Else ' empty source range
End If
End With
'Else ' source worksheet does not exist
End If
swb.Close SaveChanges:=False
swbName = Dir
Loop
'dwb.Save
Application.ScreenUpdating = True
MsgBox "Analysis backup created.", vbInformation, "Analysis Backup"
End Sub

Related

VBA Copy data from the file I select to the next empty row

I am trying to get data to be copy over to the next empty row. I have data starting in Cell A6. Can you please advise why my Lastrow2 is giving me an error and not copying the data to next empty row?
Dim FTO As Variant
Dim OB As Workbook
Dim Lastrow2 As Long
Lastrow2 = .Cells(.Rows.Count, "A").End(xlUp).Offset(-1).Row
Application.ScreenUpdating = False
FTO = Application.GetOpenFilename(Title:="Browse for your File & Import", FileFilter:="Excel Files (*.xls*), *xls*")
If FTO <> False Then
Set OB = Application.Workbooks.Open(FTO)
OB.Sheets(1).Range("E4:BW100").Copy
ThisWorkbook.Worksheets("Master").Range("A6" & Lastrow2).PasteSpecial xlPasteValues
OB.Close False
End If
Application.ScreenUpdating = True
I have tried modifying the lastrow function using the following code. Can I use the piece below to work on the function?
Lastrow2 = ThisWorkbook.Sheets(1).Range("A6").End(xlDown).Row + 1
Range(Selection, Selection.End(xlDown)).Select
If FTO <> False Then
Set OB = Application.Workbooks.Open(FTO)
OB.Sheets(1).Range("E4:BW100").Copy
ThisWorkbook.Worksheets("Master").Range("A6" & Lastrow2).PasteSpecial xlPasteValues
OB.Close False
End If
Application.ScreenUpdating = True
Copy Values From a Closed Workbook
The Issue
The expression LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Offset(-1).Row is wrong because of the -1 and could only work in a With statement:
Dim FirstRow As Long
With ThisWorkbook.Sheets("Master")
FirstRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Row
End With
or, if you need the first cell
Dim FirstCell As Range
With ThisWorkbook.Sheets("Master")
Set FirstCell = .Cells(.Rows.Count, "A").End(xlUp).Offset(1)
End With
These leading dots tell us that these cells or rows are located in the worksheet Master in the workbook containing this code (ThisWorkbook).
An Improvement
Sub CopyValues()
' Define constants.
' The Source workbook will be opened using 'Application.GetOpenFilename'.
Const SRC_WORKSHEET_INDEX As Long = 1
Const SRC_RANGE As String = "E4:BW100"
' The Destination workbook is the workbook containing this code.
Const DST_WORKSHEET_NAME As String = "Master"
Const DST_COLUMN As String = "A"
Application.ScreenUpdating = False
' Open the Source file (or not).
Dim SourcePath: SourcePath = Application.GetOpenFilename( _
Title:="Browse for your File & Import", _
FileFilter:="Excel Files (*.xls*), *xls*")
If VarType(SourcePath) = vbBoolean Then Exit Sub ' i.e. 'False'
' Reference the Source range.
Dim swb As Workbook: Set swb = Workbooks.Open(SourcePath)
Dim sws As Worksheet: Set sws = swb.Worksheets(SRC_WORKSHEET_INDEX)
Dim srg As Range: Set srg = sws.Range(SRC_RANGE)
' Reference the Destination range.
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Sheets(DST_WORKSHEET_NAME)
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, DST_COLUMN).End(xlUp).Offset(1)
Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
' Copy values.
drg.Value = srg.Value
' Close the Source file.
swb.Close False
Application.ScreenUpdating = True
End Sub

search header loop through in multiple files if matched then copy entire column and paste into single column

I have multiple workbooks in a Folder around 8 and there are Similar columns in some of these workbooks.
For Example:
There are 6 Workbooks out of 8 have similar column which Header name is "SouthRecord" i want to search that header in 1st row of each workbook if finds then copy that entire column from multiple workbooks availble in Folder and Paste appended result into an open workbook where from code is being run.
Code is copeing tha data but getting error on this line LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row Object variable and with block variable not set.
If 4 workbooks has Same Header then these 4 column will be pasted into open workbook as single column.
I would appreciate your help.
Sub MultipleSimilarColinto_1()
Dim xFd As FileDialog
Dim xFdItem As String
Dim xFileName As String
Dim wbk As Workbook
Dim sht As Worksheet
Dim twb As Workbook
Dim LastRow As Long
Dim ws As Worksheet
Dim desWS As Worksheet
Dim colArr As Variant
Dim order As Long
Dim i As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.View = xlNormalView
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
Set twb = ActiveWorkbook
Set desWS = twb.Sheets("Sheet1")
If xFd.Show Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
Else
Beep
Exit Sub
End If
xFileName = Dir(xFdItem & "*.xlsx")
Do While xFileName <> ""
Set wbk = Workbooks.Open(xFdItem & xFileName)
colArr = Array("MD")
For Each ws In wbk.Sheets
If ws.Name <> "Sheet1" Then
LastRow = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For i = LBound(colArr) To UBound(colArr)
order = ws.Rows(1).Find("MD", LookIn:=xlValues, lookat:=xlWhole).Column
ws.Range(ws.Cells(2, order), ws.Cells(LastRow, order)).Copy desWS.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
Next i
End If
Next ws
wbk.Close SaveChanges:=True
xFileName = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Import Columns From Workbooks
Option Explicit
Sub ImportColumns()
' Source
Const sFilePattern As String = "*.xlsx"
Const sExceptionsList As String = "Sheet1" ' comma-separated, no spaces
Const sHeader As String = "SouthRecord"
Const sHeaderRow As Long = 1
' Destination
Const dColumn As String = "A"
' Source
Dim sfd As FileDialog
Set sfd = Application.FileDialog(msoFileDialogFolderPicker)
'sfd.InitialFileName = "C:\Test\"
Dim sFolderPath As String
If sfd.Show Then
sFolderPath = sfd.SelectedItems(1) & Application.PathSeparator
Else
'MsgBox "You canceled.", vbExclamation
Beep
Exit Sub
End If
Dim sFileName As String: sFileName = Dir(sFolderPath & sFilePattern)
If Len(sFileName) = 0 Then
'MsgBox "No files found.", vbExclamation
Beep
Exit Sub
End If
Dim sExceptions() As String: sExceptions = Split(sExceptionsList, ",")
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.ActiveSheet ' improve!
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, dColumn).End(xlUp).Offset(1)
' Loop.
Application.ScreenUpdating = False
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
Dim shrg As Range
Dim sData() As Variant
Dim sfCell As Range
Dim slCell As Range
Dim srCount As Long
Dim wsCount As Long
Do While Len(sFileName) > 0
Set swb = Workbooks.Open(sFolderPath & sFileName)
For Each sws In swb.Worksheets
If IsError(Application.Match(sws.Name, sExceptions, 0)) Then
Set shrg = sws.Rows(sHeaderRow)
Set sfCell = shrg.Find(sHeader, shrg.Cells(shrg.Cells.Count), _
xlFormulas, xlWhole)
If Not sfCell Is Nothing Then
Set sfCell = sfCell.Offset(1)
Set slCell = sfCell _
.Resize(sws.Rows.Count - sHeaderRow) _
.Find("*", , xlFormulas, , , xlPrevious)
If Not slCell Is Nothing Then
srCount = slCell.Row - sHeaderRow
Set srg = sfCell.Resize(srCount)
End If
End If
If srCount > 0 Then
If srCount = 1 Then
ReDim sData(1 To 1, 1 To 1): sData(1, 1) = srg.Value
Else
sData = srg.Value
End If
dfCell.Resize(srCount).Value = sData
Set dfCell = dfCell.Offset(srCount)
wsCount = wsCount + 1
srCount = 0
End If
End If
Next sws
swb.Close SaveChanges:=False
sFileName = Dir
Loop
' Save the destination workbook.
'dwb.Save
Application.ScreenUpdating = True
MsgBox wsCount & " '" & sHeader & "' columns copied.", vbInformation
End Sub

Fix Subscript out of range VBA

I am try to copy formula and header contained in range "T12:W13" and paste it in the same cell location in all files in a folder. Cop to destination "T12:W13" then drag the formula all the way down close and save the sheet and then open next sheet till all the files in the folder are done.
Sub CopyRange()
Application.ScreenUpdating = False
Dim wkbDest As Workbook
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Const strPath As String = "C:\Users\kaii\Downloads\Jan 2022\"
ChDir strPath
strExtension = Dir("*.xlsx*")
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath & strExtension)
With wkbSource
.Sheets("Monthly").Range("T12:W13").Copy wkbDest.Sheets("XXTOLL_Collector_Invoice_*").Range("T12").Paste
ActiveCell.AutoFill Range(ActiveCell, ActiveCell.Offset(0, -1).End(xlDown).Offset(0, 1))
.Close savechanges:=False
End With
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.CutCopyMode = False
End Sub
Copy Columns (Headers, Formulas, Last Row) to Worksheets
Option Explicit
Sub CopyColumns()
' Source ('ThisWorkook')
Const sName As String = "Monthly"
Const sAddress As String = "T12:W13"
' Destination (Opening Workbooks)
Const dFolderPath As String = "C:\Users\kaii\Downloads\Jan 2022\"
Const dFileExtension As String = ".xlsx"
Const dFilePattern As String = "*"
Const dNameLeft As String = "XXTOLL_Collector_Invoice_"
Const dAddress As String = "T12:W13"
Dim dFileName As String
dFileName = Dir(dFolderPath & dFilePattern & dFileExtension)
If Len(dFileName) = 0 Then
MsgBox "No files found.", vbExclamation
Exit Sub
End If
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets(sName)
Dim srg As Range: Set srg = sws.Range(sAddress)
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim dws As Worksheet
Dim drg As Range
Dim dlrCell As Range
Do While Len(dFileName) > 0
Set dwb = Workbooks.Open(dFolderPath & dFileName)
For Each dws In dwb.Worksheets
If InStr(1, dws.Name, dNameLeft, vbTextCompare) = 1 Then ' begins w
Set drg = dws.Range(dAddress)
srg.Copy drg
Set dlrCell = dws.UsedRange _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
With drg.Resize(1).Offset(1)
.Resize(dlrCell.Row - .Row + 1).Formula = .Formula
End With
End If
Next dws
dwb.Close SaveChanges:=True
dFileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Columns copied.", vbInformation
End Sub

VBA to Consolidate data from folder to single sheet in Excel

I just found the below vba code from this forum and trying to include column headers of the excel files to be copied but no luck. please help.
Sub ConsolidateWorkbooks()
Dim FolderPath As String, Filename As String, sh As Worksheet, ShMaster As Worksheet
Dim wbSource As Workbook, lastER As Long, arr
'adding a new sheet on ThisWorkbook (after the last existing one)
Set ShMaster = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Sheets.count))
Application.ScreenUpdating = False
FolderPath = "P:\FG\03_OtD_Enabling\Enabling\Teams\Enabling_RPA\Other Automations\Excel Merge Several Files\Data\"
Filename = Dir(FolderPath & "*.xls*")
Do While Filename <> ""
'set the workbook to be open:
Set wbSource = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
For Each sh In ActiveWorkbook.Worksheets 'iterate between its sheets
lastER = ShMaster.Range("A" & rows.count).End(xlUp).row 'last empty row
'put the sheet range in an array:
arr = sh.Range(sh.UsedRange.cells(1, 1).Offset(1, 0), _
sh.cells(sh.UsedRange.rows.count - sh.UsedRange.row + 1, _
sh.UsedRange.Columns.count)).Value
'drop the array content at once:
ShMaster.Range("A" & lastER).Resize(UBound(arr), UBound(arr, 2)).Value = arr
Next sh
wbSource.Close 'close the workbook
Filename = Dir() 'find the next workbook in the folder
Loop
Application.ScreenUpdating = True
End Sub
Consolidate Workbooks
This will copy only the headers of each first worksheet of each workbook.
If you meant to copy the headers of each worksheet, it becomes much simpler i.e. surg, srCount and sIsFirstWorksheet become redundant:
For Each sws In swb.Worksheets
Set srg = sws.UsedRange
dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value
Set dCell = dCell.Offset(srg.Rows.Count)
Next sws
If you want one or more empty rows between the data sets, you can easily implement a constant (e.g. Const Gap As Long = 1) and add it to the 'offset part':
Set dCell = dCell.Offset(srCount + Gap)
Option Explicit
Sub ConsolidateWorkbooks()
Const ProcTitle As String = "Consolidate Workbooks"
Const sFolderPath As String = "P:\FG\03_OtD_Enabling\Enabling\Teams\" _
& "Enabling_RPA\Other Automations\Excel Merge Several Files\Data\"
Const sFilePattern As String = "*.xls*"
' Source (Are there any files?)
Dim sFileName As String: sFileName = Dir(sFolderPath & sFilePattern)
If Len(sFileName) = 0 Then
MsgBox "No files to process.", vbCritical, ProcTitle
Exit Sub
End If
Application.ScreenUpdating = False
' Destination (Workbook - Worksheet - Range (First Cell))
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet ' note 'Worksheets vs Sheets':
Set dws = dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count))
Dim dCell As Range
Set dCell = dws.Cells(dws.Rows.Count, 1).End(xlUp).Offset(1)
' Source (Variables)
Dim swb As Workbook
Dim sws As Worksheet
Dim surg As Range
Dim srg As Range
Dim srCount As Long
Dim sFilePath As String
Dim sIsFirstWorksheet As Boolean
Do While Len(sFileName) > 0
sFilePath = sFolderPath & sFileName
Set swb = Workbooks.Open(Filename:=sFilePath, ReadOnly:=True)
sIsFirstWorksheet = True
For Each sws In swb.Worksheets
Set surg = sws.UsedRange
If sIsFirstWorksheet Then ' copy headers
srCount = surg.Rows.Count
Set srg = surg
sIsFirstWorksheet = False
Else ' don't copy headers
srCount = surg.Rows.Count - 1
Set srg = surg.Resize(srCount).Offset(1)
End If
dCell.Resize(srCount, srg.Columns.Count).Value = srg.Value
Set dCell = dCell.Offset(srCount)
Next sws
swb.Close SaveChanges:=False
sFileName = Dir
Loop
'dwb.Save
Application.ScreenUpdating = True
MsgBox "Workbooks consolidated.", vbInformation, ProcTitle
End Sub

Browse and copy Data from SELECTED File with dynamic range

I have this code to browse files from another workbook. then when i get the file, paste it on sheet1 range A10.
when I go back looking for the next workbook, all I want is to paste that data in the next cell.
It's like copying and pasting with dynamic ranges, how to do that?
the thing is, my code will just overwrite the data i pasted earlier in the A10 range. obviously this is not what I want.
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A1:E20").Copy
ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
OpenBook.Close False
Sheet2.Range("A10").Select
End If
Application.ScreenUpdating = True
End Sub
if there is allways have data on 'A' row, then it would be work
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A1:E20").Copy
'----------------------------------------
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("SelectFile")
Dim nextRow As Integer
nextRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
If nextRow = 0 Then nextRow = 10
'----------------------------------------
ws.Range("A" & nextRow).PasteSpecial xlPasteValues
OpenBook.Close False
Sheet2.Range("A" & nextRow).Select
End If
Application.ScreenUpdating = True
End Sub
Copy Range From Another Workbook
Option Explicit
Sub Get_Data_From_File()
' Source
Const sID As Variant = 1
Const sRange As String = "A1:E20"
' Destination
Const dName As String = "SelectFile"
Const dFirst As String = "A10"
' Open Source
Dim swbName As Variant
swbName = Application.GetOpenFilename( _
Title:="Browse for your File & Import Range", _
FileFilter:="Excel Files (*.xls*),*xls*")
If swbName = False Then Exit Sub
Application.ScreenUpdating = False
' Source
Dim swb As Workbook: Set swb = Workbooks.Open(swbName)
Dim srg As Range: Set srg = swb.Worksheets(sID).Range(sRange)
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
With dws.Range(dFirst)
Dim rg As Range
Set rg = .Resize(.Worksheet.Rows.Count - .Row + 1, _
.Worksheet.Columns.Count - .Column + 1)
Dim lCell As Range
Set lCell = rg.Find("*", , xlFormulas, , xlByRows, xlPrevious)
Dim dCell As Range
If lCell Is Nothing Then
Set dCell = .Offset
Else
Set dCell = .Offset(lCell.Row - .Row + 1)
End If
End With
' Copy
dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value
' Close
swb.Close False
' Finishing Touches
dwb.Activate
dws.Activate
ActiveWindow.ScrollRow = dCell.Row
ActiveWindow.ScrollColumn = dCell.Column
dCell.Select
Application.ScreenUpdating = True
End Sub

Resources