Copy rows from multiple workbooks based on cell value - excel

How do I copy cells from a workbook based on a cell-value.
In the excel file that needs to be filled, column B contains a part of a filename in which the data can be found.
B2 contains 312123-145
B3 contains 312123-195
etc,
normally around 18rows, but the loop/step can go until a empty cell if found
The workbook the data contains is the cell-value.xlsm
There is a sheet with name Yield in the 312123-145.xlsm
From that sheet I would like to copy A2:N2, and paste that data at the main excel sheet, in columns E:R in the corrosponding row.
I don't know how to start on to look-up a cell value and find the file with the correct data and then how do I step to the next row.
This the code I started with, I hardcoded first all cellvalues to keep it simple.
Sub ImportWorksheet()
' This macro will import a file into this workbook
Sheets("Sheet1").Select
PathName = "C:\Documents\test\"
Filename = "312123-195"
TabName = "Yield"
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=PathName & Filename
ActiveSheet.Name = TabName
Sheets(TabName).Copy After:=Workbooks(ControlFile).Sheets(1)
Windows(Filename).Activate
ActiveWorkbook.Close SaveChanges:=False
Windows(ControlFile).Activate
End Sub

Import Data From Closed Workbooks
Option Explicit
Sub ImportData()
Dim sFolderPath As String: sFolderPath = "C:\Documents\test\"
Dim sFileExtension As String: sFileExtension = ".xlsm" ' ".xls*"
Const sName As String = "Yield"
Const srgAddress As String = "A2:N2"
Const sFileDelimiter As String = "-"
Const dName As String = "Sheet1"
Const dlCol As String = "B" ' Lookup
Const dvCol As String = "E" ' Value
Const dfRow As Long = 2
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
If Left(sFileExtension, 1) <> "." Then sFileExtension = "." & sFileExtension
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
Dim dlRow As Long: dlRow = dws.Cells(dws.Rows.Count, dlCol).End(xlUp).Row
If dlRow < dfRow Then Exit Sub ' no data
Dim dlrg As Range
Set dlrg = dws.Range(dws.Cells(dfRow, dlCol), dws.Cells(dlRow, dlCol))
Dim dcCount As Long: dcCount = dws.Range(srgAddress).Columns.Count
Dim dvrg As Range: Set dvrg = dws.Cells(dfRow, dvCol).Resize(, dcCount)
Dim swb As Workbook
Dim sws As Worksheet
Dim sFilePattern As String
Dim sFileName As String
Dim dlCell As Range
Dim swsCount As Long
Application.ScreenUpdating = False
For Each dlCell In dlrg.Cells
sFilePattern = sFolderPath & Left(CStr(dlCell.Value), _
InStr(1, CStr(dlCell.Value), sFileDelimiter, vbTextCompare) - 1) _
& sFileExtension
sFileName = Dir(sFilePattern)
If Len(sFileName) > 0 Then ' file (workbook) exists
Set swb = Workbooks.Open(sFolderPath & sFileName)
On Error Resume Next
Set sws = swb.Worksheets(sName)
On Error GoTo 0
If Not sws Is Nothing Then ' worksheet exists
dvrg.Value = sws.Range(srgAddress).Value
swsCount = swsCount + 1
End If
swb.Close SaveChanges:=False
End If
Set dvrg = dvrg.Offset(1)
Next dlCell
Application.ScreenUpdating = True
Select Case swsCount
Case 0
MsgBox "No data imported", vbCritical
Case 1
MsgBox "Data imported from one worksheet.", vbInformation
Case Else
MsgBox "Data imported from " & swsCount & " worksheets.", vbInformation
End Select
End Sub

Related

Looping through folder and copying csv with a certain name into active workbook

I am trying to loop through a folder containing different csv files and copying the ones with the prefix AB. However, my loop gets stuck on the second file it finds and copies and pastes it continuously. Does anyone find where this could be happening?
Do Until Dir(filepath & "*") = ""
' defining path and file names
abfilename = Dir(filepath & "AB" & "*")
abfilepath = filepath & "AB" & "*"
' if pathname doesnt return files then quit and clear contents
If Len(abfilename) = 0 Then
' ThisWorkbook.Sheets("AB_*").Range("A:Z").ClearContents
MsgBox "The data folder has no SW files"
Exit Sub
' AB files found and copied
ElseIf abfilename <> "" Then
MsgBox "File Found"
' iterate while there are files with SW prefix
While Dir(abfilepath) <> ""
' Copying into worksheet
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
abfilename_stripped = Replace(abfilename, ".csv", "")
Set ws = ThisWorkbook.Sheets(abfilename_stripped)
Workbooks.Open abfilepath, Local:=True ' Open the csv
MsgBox abfilename
Set csv = ActiveWorkbook ' Create object of csv workbook
csv.ActiveSheet.Range("A:Z").Copy ' Copy all cells
MsgBox "File Copied"
ws.Activate ' Go back to pasting sheet
ws.Range("A1").PasteSpecial xlPasteValues 'Pasting Values
MsgBox "File Pasted"
csv.Close ' Closing open csv
Set csv = Nothing
swfilename = Dir()
Wend
End If
Your issue is While Dir(abfilepath) <> "" - this resets the file search every time.
Instead, your loop should look like so:
filefound=Dir(abfilepath)
While filefound<>"" Then
'do stuff with file
filefound=Dir 'looks for next file
Wend
Import Data From Closed Workbooks To Existing Worksheets
Option Explicit
Sub ImportData()
Const SRC_FOLDER_PATH As String = "C:\Test"
Const SRC_FILE_PATTERN As String = "AB*.csv"
Const SRC_COPY_COLUMNS As String = "A:Z"
Const DST_FIRST_CELL As String = "A1"
Dim pSep As String: pSep = Application.PathSeparator
Dim sFolderPath As String
sFolderPath = SRC_FOLDER_PATH & IIf(Right(SRC_FOLDER_PATH, 1) = pSep, "", pSep)
Dim sFileName As String: sFileName = Dir(sFolderPath & SRC_FILE_PATTERN)
If Len(sFileName) = 0 Then
MsgBox "No files matching """ & SRC_FILE_PATTERN & """ in """ _
& sFolderPath & """ found.", vbCritical
Exit Sub
End If
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim ColumnsCount As Long ' is always the same;...
ColumnsCount = dwb.Worksheets(1).Columns(SRC_COPY_COLUMNS).Columns.Count
Application.ScreenUpdating = False
Dim swb As Workbook, sws As Worksheet, srg As Range, sFilePath As String
Dim dws As Worksheet, drg As Range, dfCell As Range, dName As String
Dim RowsCount As Long ' ...may (will) be different
Do While Len(sFileName) > 0
' The source file base name, the name without the file extension,
' becomes the destination worksheet name.
dName = Left(sFileName, InStrRev(sFileName, ".") - 1)
On Error Resume Next
Set dws = dwb.Sheets(dName)
On Error GoTo 0
If Not dws Is Nothing Then ' destination sheet exists
sFilePath = sFolderPath & sFileName
Set swb = Workbooks.Open(Filename:=sFilePath, Local:=True)
Set sws = swb.Sheets(1) ' the one and only ('.csv')
With sws.UsedRange.EntireRow ' restrict to the last...
RowsCount = .Row + .Rows.Count - 1 ' ... row of the used range
Set srg = sws.Columns(SRC_COPY_COLUMNS).Resize(RowsCount)
End With
Set dfCell = dws.Range(DST_FIRST_CELL)
' The destination range needs to be of the same size
' as the source range...
Set drg = dfCell.Resize(RowsCount, ColumnsCount)
' ... to be able to copy like this:
drg.Value = srg.Value ' the most efficient way to copy values
drg.Resize(dws.Rows.Count - drg.Row - RowsCount + 1) _
.Offset(RowsCount).ClearContents ' clear below
swb.Close SaveChanges:=False ' it was just read (copied) from
Set dws = Nothing ' reset for the next iteration
'Else ' destination sheet doesn't exist; do nothing!?
End If
sFileName = Dir ' next source file (workbook) name
Loop
Application.ScreenUpdating = True
MsgBox "Data imported.", vbInformation
End Sub

I have multiple xlsx file(which are not opened. I want to copy range value of one Workbook to in single column of new workbook

how it is possible?
Dim Ws1, Ws2
Dim Wb1, wb2
Set Wb1 = ThisWorkbook
Set wb2 = Workbooks("test1.xlsx")
wb2.Worksheets("Sheet1").Range("A4").Copy Wb1.Worksheets("Sheet1").Range("B4")
wb2.Worksheets("Sheet1").Range("B10").Copy Wb1.Worksheets("Sheet1").Range("C4")
:
:
wbn.Worksheets("Sheet1").Range("An").Copy Wb1.Worksheets("Sheet1").Range("Bn")
Retrieve Data From Closed Workbooks
Sub RetrieveDataFromClosedWorkbooks()
' Define constants.
' Source
Const SOURCE_FOLDER_PATH As String = "C:\Test"
Const SOURCE_FILE_PATTERN As String = "*.xlsx"
Const SOURCE_WORKSHEET_NAME As String = "Sheet1"
Const SOURCE_CELL_ADDRESSES As String = "A4,B10" ' add more
' Destination
Const DESTINATION_WORKSHEET_NAME As String = "Sheet1"
Const DESTINATION_FIRST_CELL_ADDRESS As String = "B4"
' Source
Dim sFolderPath As String: sFolderPath = SOURCE_FOLDER_PATH
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFileName As String: sFileName = Dir(sFolderPath & SOURCE_FILE_PATTERN)
If Len(sFileName) = 0 Then
MsgBox "No files found.", vbExclamation
Exit Sub
End If
Dim sAddresses() As String: sAddresses = Split(SOURCE_CELL_ADDRESSES, ",")
Dim saUpper As Long: saUpper = UBound(sAddresses)
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets(DESTINATION_WORKSHEET_NAME)
Dim dCell As Range: Set dCell = dws.Range(DESTINATION_FIRST_CELL_ADDRESS)
' Loop.
Dim sa As Long
Do Until Len(sFileName) = 0
For sa = 0 To saUpper
With dCell.Offset(sa)
.Value = "='" & sFolderPath & "[" & sFileName & "]" _
& SOURCE_WORKSHEET_NAME & "'!" & sAddresses(sa)
' If you don't want to keep the formulas,
' uncomment the following line.
'.Value = .Value
End With
Next sa
Set dCell = dCell.Offset(, 1) ' next column
sFileName = Dir ' next file
Loop
' Inform.
MsgBox "Data retrieved.", vbInformation
End Sub

VBA code to copy paste data from multiple source workbooks to a master data workbook (Master data sheet) based on column headers

My code below browses through the folder and effectively picks out the required files but the copy paste codes that I have tried did not work for me. Cant use traditional copy paste as column order is not same. Column names are same though.
Sub ImportExcelfiles()
Dim strPath As String
Dim strFile As String
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim bookName As Worksheet
Dim rowCountSource As Long
Dim colCountSource As Long
Dim rowOutputTarget As Long
Dim colOutputTarget As Long
'Variables for Sheet - Workbook Name
Dim nameCount As Long
Dim fileName As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'====================================
'SET THE PATH AND FILE TO THE FOLDER
'====================================
strPath = ThisWorkbook.Worksheets("Control").Range("C4")
fileName = ThisWorkbook.Worksheets("Control").Range("C5")
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
'set the target worksheet
Set wsTarget = ThisWorkbook.Worksheets("Master Data")
Set bookName = ThisWorkbook.Worksheets("Workbook Name")
'set the initial output row and column count for master data and workbook name
rowOutputTarget = 2
nameCount = 2
'get the first file
strFile = Dir(strPath & "*.xlsx*")
'loop throught the excel files in the folder
Do While strFile <> ""
If InStr(strFile, fileName) > 0 Then
'open the workbook
Set wbSource = Workbooks.Open(strPath & strFile)
Set wsSource = wbSource.Worksheets("Details")
'get the row and column counts
With wsSource
'row count based on column 1 = A
rowCountSource = .Cells(.Rows.Count, 1).End(xlUp).Row
'column count based on row 1
colCountSource = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
-------------------------------Need help here to copy paste-------------------------------------
'copy and paste from A2
wsSource.Range("A3", "AD" & rowCountSource).Copy
wsTarget.Range("A" & rowOutputTarget).PasteSpecial
Paste:=xlPasteValues
bookName.Range("A" & nameCount).Value = wbSource.Name
nameCount = nameCount + 1
rowOutputTarget = rowOutputTarget + rowCountSource - 2
'close the opened workbook
wbSource.Close SaveChanges:=False
End If
'get the next file
strFile = Dir()
Loop
End Sub
Since the order of the columns is different you have to copy them one at a time.
Sub ImportExcelfiles()
Const ROW_COLNAME = 3
'Variables for Sheet - Workbook Name
Dim wbSource As Workbook
Dim wsTarget As Worksheet, wsName As Worksheet
Dim rowOutputTarget As Long, nameCount As Long
Dim strPath As String, strFile As String, fileName As String
With ThisWorkbook
'set the file and path to folder
strPath = .Sheets("Control").Range("C4")
fileName = .Sheets("Control").Range("C5")
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
'set the target and name worksheets
Set wsTarget = .Sheets("Master Data")
Set wsName = .Sheets("Workbook Name")
End With
' fill dictionary column name to column number from row 1
Dim dict As Object, k As String, rng As Range
Dim lastcol As Long, lastrow As Long, i As Long, n As Long
Set dict = CreateObject("Scripting.Dictionary")
With wsTarget
lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
For i = 1 To lastcol
k = UCase(Trim(.Cells(1, i)))
dict.Add k, i
Next
End With
'set the initial output row and column count for master data and workbook nam
rowOutputTarget = 2
nameCount = 2
'get the first file
strFile = Dir(strPath & "*.xlsx*")
'loop through the excel files in the folder
Dim ar, arH, ky, bHasData
Application.ScreenUpdating = False
Do While strFile <> ""
If InStr(strFile, fileName) > 0 Then
'open the workbook
Set wbSource = Workbooks.Open(strPath & strFile, False, False)
wsName.Range("A" & nameCount).Value = wbSource.Name
nameCount = nameCount + 1
' copy values to arrays
With wbSource.Sheets("Details")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
arH = .Range("A1:AD1").Offset(ROW_COLNAME - 1).Value2 ' col names
ar = .Range("A" & ROW_COLNAME & ":AD" & lastrow).Value2
End With
'close the opened workbook
wbSource.Close SaveChanges:=False
' copy each columns
If lastrow > ROW_COLNAME Then
bHasData = False
For n = 1 To UBound(ar, 2)
k = UCase(Trim(arH(1, n)))
' determine target column using dictonary
' as lookup with approx match
i = 0
For Each ky In dict
If InStr(1, k, ky) > 0 Then
i = dict(ky)
Exit For
End If
Next
' valid match
If i > 0 Then
bHasData = True
Set rng = wsTarget.Cells(rowOutputTarget, i).Resize(UBound(ar))
' copy column n of array to column i of target sheet
rng.Value2 = Application.Index(ar, 0, n)
ElseIf Len(k) > 0 Then
Debug.Print "Column '" & k & "' not found " & strFile
End If
Next
If bHasData Then
rowOutputTarget = rowOutputTarget + UBound(ar) + 2
End If
End If
'get the next file
strFile = Dir()
End If
Loop
Application.ScreenUpdating = True
MsgBox nameCount - 2 & " books", vbInformation
End Sub
Import Data From Files in Folder
Option Explicit
Sub ImportExcelfiles()
' Source
Const sName As String = "Details"
Const siFileExtensionPattern As String = ".xlsx" ' maybe ".xls?" ?
Const sfCol As String = "A"
Const slCol As String = "AD"
Const sfRow As Long = 3
' Destination
Const dName As String = "Master Data"
Const dfCellAddress As String = "A2"
' Destination Lookup
Const dlName As String = "Control"
Const dlsFolderPathAddress As String = "C4"
Const dlsFileNamePatternAddress As String = "C5"
' Destination Name
Const dnName As String = "Workbook Name"
Const dnfCellAddress As String = "A2"
Dim dwb As Workbook: Set dwb = ThisWorkbook
' Destination Lookup Worksheet
' (contains the folder path and the partial file name)
Dim dlws As Worksheet: Set dlws = dwb.Worksheets(dlName)
Dim sFolderPath As String: sFolderPath = dlws.Range(dlsFolderPathAddress)
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFileNamePattern As String ' contains i.e. leading and trailing '*'
sFileNamePattern = "*" & dlws.Range(dlsFileNamePatternAddress) & "*"
Dim sFileExtensionPattern As String
sFileExtensionPattern = siFileExtensionPattern
If Left(sFileExtensionPattern, 1) <> "." Then _
sFileExtensionPattern = "." & sFileExtensionPattern
Dim sFileName As String
sFileName = Dir(sFolderPath & sFileNamePattern & sFileExtensionPattern)
If Len(sFileName) = 0 Then
MsgBox "No files found.", vbCritical ' improve!
Exit Sub
End If
' Destination Worksheet (source data will by copied to)
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
' Source and Destination Columns Count
Dim cCount As Long
cCount = dws.Columns(slCol).Column - dws.Columns(sfCol).Column + 1
' Destination First Row Range
Dim dfrrg As Range: Set dfrrg = dws.Range(dfCellAddress).Resize(, cCount)
' Destination Name Worksheet (source workbook names will be written to)
Dim dnws As Worksheet: Set dnws = dwb.Worksheets(dnName)
' Destination Name Cell
Dim dnCell As Range: Set dnCell = dnws.Range(dnfCellAddress)
Application.ScreenUpdating = False
' Source
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
Dim slRow As Long
' Destination
Dim drg As Range
' Both
Dim rCount As Long
Do While Len(sFileName) > 0
Set swb = Workbooks.Open(sFolderPath & sFileName)
' Attempt to reference the source worksheet.
On Error Resume Next
Set sws = swb.Worksheets("Details")
On Error GoTo 0
If Not sws Is Nothing Then ' worksheet exists
slRow = sws.Cells(sws.Rows.Count, sfCol).End(xlUp).Row
If slRow >= sfRow Then ' found data in column
rCount = slRow - sfRow + 1
Set srg = sws.Cells(sfRow, sfCol).Resize(rCount, cCount)
Set drg = dfrrg.Resize(rCount)
drg.Value = srg.Value
dnCell.Value = swb.Name
' Reset
Set dfrrg = dfrrg.Offset(rCount)
Set dnCell = dnCell.Offset(1)
'Else ' found no data in column; do nothing
End If
Set sws = Nothing
'Else ' worksheet doesn't exist; do nothing
End If
swb.Close SaveChanges:=False
sFileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Data imported.", 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

Append data after last row

My macro is to append the values from three sheets in a weekly report workbook to the values in equivalent sheets in an accumulating workbook.
However, I cannot define the ranges in the ThisWorkbook.Sheets correctly - Only the cell A2 values from the wb.Sheets are appended.
Could someone please help me define the range correctly? Many thanks!
Sub Import_SheetData_ThisWorkbook()
Dim lRow As Long, lRow1 As Long, lRow2 As Long, lRow3 As Long
Dim Path As String, WeeklyCollation As String
Dim wkNum As Integer
Dim wb As Workbook
wkNum = Application.InputBox("Enter week number")
Path = "C:\xyz\"
WeeklyCollation = Path & "Activities 2021 w" & wkNum & ".xlsx"
lRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
Set wb = Workbooks.Open(WeeklyCollation)
lRow1 = wb.Sheets("Customer visits").Cells(Rows.Count, 1).End(xlUp).Row
lRow2 = wb.Sheets("Orders").Cells(Rows.Count, 1).End(xlUp).Row
lRow3 = wb.Sheets("Visits").Cells(Rows.Count, 1).End(xlUp).Row
'Replace with copy and paste
'Can't define range in ThisWorkbook
ThisWorkbook.Sheets("Customer visits").Range("A" & lRow + 1).Value = wb.Sheets("Customer visits").Range("A2:H" & lRow1).Value
ThisWorkbook.Sheets("Orders").Range("A" & lRow + 1).Value = wb.Sheets("Orders").Range("A2:I" & lRow2).Value
ThisWorkbook.Sheets("Visits").Range("A" & lRow + 1).Value = wb.Sheets("Visits").Range("A2:F" & lRow3).Value
wb.Close SaveChanges:=False
MsgBox ("Data added")
End Sub
Backup Data
Adjust the values in the constants section.
Option Explicit
Sub ImportSheetData()
' Constants
' Source
Const sPath As String = "C:\xyz\"
Const swsNamesList As String = "Customer visits,Orders,Visits"
Const slrCol As String = "A"
Const sfRow As Long = 2
' Destination
Const dwsNamesList As String = "Customer visits,Orders,Visits"
Const dlrCol As String = "A"
' Both
Const Cols As String = "A:H"
' Create the references to the workbooks.
Dim wkNum As Variant: wkNum = Application.InputBox( _
"Enter week number", "Import Sheet Data", , , , , , 1)
If wkNum = False Then
MsgBox "You canceled.", vbExclamation
Exit Sub
End If
Dim sWeeklyCollation As String
sWeeklyCollation = sPath & "Activities 2021 w" & wkNum & ".xlsx"
Dim swb As Workbook
On Error Resume Next
Set swb = Workbooks.Open(sWeeklyCollation)
On Error GoTo 0
If swb Is Nothing Then
MsgBox "Could not find the file '" & sWeeklyCollation & "'.", vbCritical
Exit Sub
End If
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
' Copy the data.
Dim swsNames() As String: swsNames = Split(swsNamesList, ",")
Dim dwsNames() As String: dwsNames = Split(dwsNamesList, ",")
Dim sws As Worksheet
Dim srg As Range
Dim slRow As Long
Dim dws As Worksheet
Dim drg As Range
Dim dCell As Range
Dim n As Long
Dim rCount As Long
Dim wsCount As Long ' Counts the number of worksheets processed
For n = 0 To UBound(swsNames)
On Error Resume Next
Set sws = swb.Worksheets(swsNames(n))
On Error GoTo 0
If Not sws Is Nothing Then ' source worksheet exists
On Error Resume Next
Set dws = dwb.Worksheets(dwsNames(n))
On Error GoTo 0
If Not dws Is Nothing Then ' destination worksheet exists
slRow = sws.Cells(sws.Rows.Count, slrCol).End(xlUp).Row
rCount = slRow - sfRow + 1
If rCount > 0 Then ' found data in source worksheet
Set srg = sws.Columns(Cols).Resize(rCount).Offset(sfRow - 1)
Set dCell = dws.Cells(dws.Rows.Count, dlrCol) _
.End(xlUp).Offset(1)
Set drg = dCell.Resize(rCount).EntireRow.Columns(Cols)
drg.Value = srg.Value
wsCount = wsCount + 1
' Else ' no data in source worksheet
End If
'Else ' destination worksheet doesn't exist
End If
'Else ' source worksheet doesn't exist
End If
Next n
' Finishing Touches
swb.Close SaveChanges:=False
'dwb.Save
' Or:
'dwb.Close SaveChanges:=True
MsgBox "Data from " & wsCount & " worksheets added.", vbInformation
End Sub

Resources