I have multiple files I tried to merge in a single one.
I successfully did it thank you to the help of a kind soul. However, now I have to separate the information from each file into single tabs inside the same file.
Code below copy the info from multiple files on x location on my PC, and then paste it all together on one single tab using a loop. I'm trying VBA stops in every loop after paste the info, then create a new tab and paste the info and enter the code and so on.
Option Explicit
Sub Mergebytabs()
Dim wbk1 As Workbook
Set wbk1 = ThisWorkbook
Dim sFolderPath As String
sFolderPath = InputBox("Please introduce the path where files are stored", _
"Select Files' Path", "Paste path here")
If Len(sFolderPath) = 0 Then Exit Sub
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFilename As String: sFilename = Dir(sFolderPath & "*.xls*")
If Len(sFilename) = 0 Then Exit Sub
Dim dwb As Workbook: Set dwb = Workbooks.Add(xlWBATWorksheet)
Dim dws As Worksheet: Set dws = dwb.Worksheets(1)
Dim dfCell As Range
Set dfCell = dws.Range("A1")
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
Dim sFilePath As String
Dim sCount As Long
Dim siteCount As Integer
Dim ilv As Integer
Dim var1 As Worksheet
Do While Len(sFilename) > 0
Sheets.Add after:=ActiveSheet
Sheets(sCount).Activate
Set swb = Workbooks.Open(sFolderPath & sFilename)
On Error Resume Next ' test if the worksheet exists
Set sws = swb.Worksheets("Sheet1")
On Error GoTo 0
If Not sws Is Nothing Then ' worksheet exists
sCount = sCount + 1
Set srg = sws.Range("A1").CurrentRegion
srg.Copy dfCell
Set dfCell = dfCell.Offset(srg.Rows.Count)
Set sws = Nothing
siteCount = 0
For ilv = 1 To siteCount
var1 = Sheets.Add(after:=Sheets(Worksheets.Count))
var1.Name = "Sheet_Name_" & CStr(ilv)
Next ilv
'Else ' worksheet doesn't exist
End If
swb.Close SaveChanges:=False
sFilename = Dir
Loop
Copy from each file to a separate sheet.
Sub MergeByTabs()
Dim swb As Workbook, sws As Worksheet, srg As Range
Dim dwb As Workbook, dws As Worksheet
Dim n As Long, sFolderPath As String, sFilename As String
' select folder
With Application.fileDialog(msoFileDialogFolderPicker)
.InitialFileName = ThisWorkbook.Path
.Title = "Select folder ."
If .Show = False Then
MsgBox "Folder not selected"
Exit Sub
End If
sFolderPath = .SelectedItems(1)
End With
sFolderPath = sFolderPath & "\"
' create destination workbook with one sheet
Set dwb = Workbooks.Add(xlWBATWorksheet)
' loop through files
Application.ScreenUpdating = False
sFilename = Dir(sFolderPath & "*.xls*")
Do While sFilename <> ""
' open source workbook
Set swb = Workbooks.Open(sFolderPath & sFilename, ReadOnly:=True)
' test if the worksheet exists
On Error Resume Next
Set sws = swb.Worksheets("Sheet1")
On Error GoTo 0
' if sheet exists then copy data
If Not sws Is Nothing Then
' create destination sheet if required
n = n + 1
If n > dwb.Sheets.Count Then
Set dws = dwb.Sheets.Add(after:=dwb.Sheets(dwb.Sheets.Count))
Else
Set dws = dwb.Sheets(n)
End If
dws.Name = "Sheet_Name_" & CStr(n)
' copy data
Set srg = sws.Range("A1").CurrentRegion
srg.Copy dws.Range("A1")
End If
swb.Close False
' next file
sFilename = Dir
Loop
Application.ScreenUpdating = True
MsgBox n & " files processed", vbInformation
End Sub
Related
i need to make the bellow code copy even blank cell (to avoid input data from 2 workbooks in the same row), because the final output is going to be storing the data from each workbook to a single row .
`
Sub Copy_specific_Cells_From_other_workbooks_auto_RF()
Dim FileName$, sPath$
Dim wkbDest As Workbook, wkbSource As Workbook
Dim wsDest As Worksheet, wsSource As Worksheet
Application.ScreenUpdating = False
sPath = "D:\TSSRs\PO11\TSS Reports\WL TSSR\"
'sPath = "C:\Users\user\Documents\HP Laptop\Documents\Documents\Jobs\DIT\IDMB\Stack Overflow\okinawa\"
Set wkbDest = ThisWorkbook
'setting worksheet to improve readability
Set wsDest = wkbDest.Sheets("Master")
FileName = Dir(sPath)
Do While Len(FileName) > 0
'open workbook for read only
Set wkbSource = Workbooks.Open(sPath & FileName)
'setting worksheet to improve readability
Set wsSource = wkbSource.Sheets(2)
wsSource.Range("B2").Copy
wsDest.Cells(wsDest.Rows.Count, "I").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B4").Copy
wsDest.Cells(wsDest.Rows.Count, "J").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B6").Copy
wsDest.Cells(wsDest.Rows.Count, "K").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
wsSource.Range("B7").Copy
wsDest.Cells(wsDest.Rows.Count, "L").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
'not needed since we're closing the workbook; so it will be done automatically
'Application.CutCopyMode = False
wkbSource.Close SaveChanges:=False
FileName = Dir
Loop
Application.ScreenUpdating = True
End Sub
`
Copy to Rows in Another Workbook
Determine the last destination row (dRow) before the loop only once.
At the beginning of the loop, increment the destination row by one so it becomes the currently available row where all the values from the cells of the current source worksheet will be written to.
Sub RetrieveCellsData()
Const sFolderPath As String = "C:\Test\"
' The following two arrays need to have the same number of elements.
Dim sCells() As Variant: sCells = VBA.Array("B2", "B4", "B6", "B7")
Dim dColumns() As Variant: dColumns = VBA.Array("I", "J", "K", "L")
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets("Master")
' Determine the last destination row ('dRow').
Dim dRow As Long: dRow = dws.Cells(dws.Rows.Count, "I").End(xlUp).Row
' Pick another column if necessary or use another way, e.g.:
'With dws.UsedRange
' dRow = .Columns(1).Cells(.Rows.Count).Row
'End With
Dim sPath As String: sPath = sFolderPath
Dim pSep As String: pSep = Application.PathSeparator
If Right(sPath, 1) <> pSep Then sPath = sPath & pSep
Dim sFileName As String: sFileName = Dir(sPath)
If Len(sFileName) = 0 Then
MsgBox "No files found.", vbCritical
Exit Sub
End If
Dim nUpper As Long: nUpper = UBound(sCells) ' or UBound(dColumns)
Dim swb As Workbook
Dim sws As Worksheet
Dim sFilePath As String
Dim n As Long
Application.ScreenUpdating = False
Do While Len(sFileName) > 0
dRow = dRow + 1 ' All source cell values will be written to this row,
' whether they're empty or not i.e. don't 'xlUp' in the loop!
sFilePath = sPath & sFileName
Set swb = Workbooks.Open(sFilePath, , True) ' read-only
Set sws = swb.Sheets(2) ' pretty risky!
For n = 0 To nUpper
dws.Cells(dRow, dColumns(n)).Value = sws.Range(sCells(n)).Value
Next n
swb.Close SaveChanges:=False
sFileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Cells' data retrieved.", vbInformation
End Sub
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
Hi I've tried to merge multiple reports into one without success, first I set the code to let the user enter the path where folder containing multiple reports is located, and then put the code to open all and copy and paste in a new one, but no success.. VBA is not able to recognize second part and open the files.
Sub files()
Dim folderpath As String
Dim FileOpen As String
Dim DialogBox As FileDialog
Dim wbk As Workbook
Dim wbk1 As Workbook
Set wbk1 = ThisWorkbook
Dim Filename As String
folderpath = InputBox("Please introduce the path where files are stored", "Select Files' Path", "Paste path here")
FileOpen = Dir(folderpath & "\*.xls*")
Do While Len(Filename) > 0
Set wbk = Workbooks.Open(FileOpen)
wbk.Activate
Range(“A1”).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows(“Book1”).Activate
Application.DisplayAlerts = False
Dim lr As Double
lr = wbk1.Sheets(“Sheet1”).Cells(Rows.Count, 1).End(xlUp).Row
Sheets(“Sheet1”).Select
Cells(lr + 1, 1).Select
ActiveSheet.Paste
wbk.Close True
Filename = Dir
Loop
End Sub*
Copy Worksheets' Ranges to a New Workbook
Option Explicit
Sub CreateReport()
Dim sFolderPath As String
sFolderPath = InputBox("Please introduce the path where files are stored", _
"Select Files' Path", "Paste path here")
If Len(sFolderPath) = 0 Then Exit Sub
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFilename As String: sFilename = Dir(sFolderPath & "*.xls*")
If Len(sFilename) = 0 Then Exit Sub
Dim dwb As Workbook: Set dwb = Workbooks.Add(xlWBATWorksheet)
Dim dws As Worksheet: Set dws = dwb.Worksheets(1)
Dim dfCell As Range
Set dfCell = dws.Range("A1")
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
Dim sFilePath As String
Dim sCount As Long
Do While Len(sFilename) > 0
Set swb = Workbooks.Open(sFolderPath & sFilename)
On Error Resume Next ' test if the worksheet exists
Set sws = swb.Worksheets("Sheet1")
On Error GoTo 0
If Not sws Is Nothing Then ' worksheet exists
sCount = sCount + 1
If sCount = 1 Then ' with headers
Set srg = sws.Range("A1").CurrentRegion
Else ' without headers
With sws.Range("A1").CurrentRegion
Set srg = .Resize(.Rows.Count - 1).Offset(1)
End With
End If
srg.Copy dfCell
Set dfCell = dfCell.Offset(srg.Rows.Count)
Set sws = Nothing
'Else ' worksheet doesn't exist
End If
swb.Close SaveChanges:=False
sFilename = Dir
Loop
MsgBox "Report created out of " & sCount & " worksheets.", _
vbInformation, "CreateReport"
End Sub
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
I'm trying to loop through files in a folder with following path "C:\Users\Ouen\Downloads\Test" and paste each output into a new specific sheet in a MASTER workbook.
For example, the below are all the same worksbooks that each have a specific worksheet called "Annual" with different outputs:
Asset1
Asset2
Asset3
Etc
I would like to copy the whole Annual worksheet from each of the workbooks above and paste into a MASTER workbook, while being able to rename them to the following:
Asset1 - Annual
Asset2 - Annual
Asset3 - Annual
Etc
I have had some luck in copying and pasting from each workbook into the master but I'm unable to to paste each output into a new worksheet within the master and rename. Any ideas?
Sub Assets2Master()
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
xSheetName = "Annual"
xRgStr = "B1:GI100"
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
With xFileDlg
If .Show = -1 Then
xSelItem = .SelectedItems.Item(1)
Set xWorkBook = ThisWorkbook
Set xSheet = xWorkBook.Sheets("MASTER")
If xSheet Is Nothing Then
xWorkBook.Sheets.Add(after:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "MASTER"
Set xSheet = xWorkBook.Sheets("MASTER")
End If
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
If xFileName = "" Then Exit Sub
Do Until xFileName = ""
Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
xFileName = Dir()
xBook.Close
Loop
End If
End With
et xRg = xSheet.UsedRange
xRg.ClearFormats
xRg.UseStandardHeight = True
xRg.UseStandardWidth = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Copy to the end
This code will copy, if it exists, the Annual worksheet from each workbook in the folder you select via the dialog.
They will be copied to the workbook the code is in and the copied sheets will be renamed with the name of the workbook they came from appended with - Annual.
The copied sheets will be copied after the last sheet in the MASTER workbook.
Sub Assets2Master()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim dlg As Object
Dim strFileName As String
Dim strFolder As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
With dlg
If .Show = -1 Then
strFolder = .SelectedItems.Item(1)
End If
End With
Set wbDst = ThisWorkbook
strFileName = Dir(strFolder & "\*.xlsx", vbNormal)
If strFileName = "" Then Exit Sub
Do Until strFileName = ""
If strFileName <> wbDst.Name Then
Set wbSrc = Workbooks.Open(strFolder & "\" & strFileName)
' check if 'Annual' sheet exists, and if it does copy it to master workbook
If IfSheetExists("Annual", wbSrc) Then
Set wsSrc = wbSrc.Sheets("Annual")
With wbDst
wsSrc.Copy After:=.Sheets(.Sheets.Count)
.Sheets(.Sheets.Count).Name = Left(strFileName, Len(strFileName) - 5) & " - Annual"
End With
End If
wbSrc.Close SaveChanges:=False
End If
strFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Function IfSheetExists(strName As String, Optional wb As Workbook) As Boolean
' checks for the existence of a worksheet named strName in the, optional, workbook wb
' if wb not stated checks in the active workbook
Dim ws As Worksheet
If wb Is Nothing Then
Set wb = ActiveWorkbook
End If
For Each ws In wb.Sheets
If ws.Name = strName Then
IfSheetExists = True
Exit For
End If
Next ws
End Function
Copy after specific sheet
This code is basically identical to the previous code but the workheets will be copied after a specific worksheet in the MASTER workbook.
Option Explicit
Sub Assets2Master()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim dlg As Object
Dim strFileName As String
Dim strFolder As String
Dim lngDstIndex As Long
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
With dlg
If .Show = -1 Then
strFolder = .SelectedItems.Item(1)
End If
End With
Set wbDst = ThisWorkbook
' change Specific Tab to the name ypu want the sheets to be copied after
lngDstIndex = wbDst.Sheets("Specific Tab").Index
strFileName = Dir(strFolder & "\*.xlsx", vbNormal)
If strFileName = "" Then Exit Sub
Do Until strFileName = ""
If strFileName <> wbDst.Name Then
Set wbSrc = Workbooks.Open(strFolder & "\" & strFileName)
' check if 'Annual' sheet exists, and if it does copy it to master workbook
If IfSheetExists("Annual", wbSrc) Then
Set wsSrc = wbSrc.Sheets("Annual")
With wbDst
' copy sheet to MASTER workbook
wsSrc.Copy After:=.Sheets(.Sheets.Count)
' rename sheet and move it after specified sheet
With .Sheets(.Sheets.Count)
.Name = Left(strFileName, Len(strFileName) - 5) & " - Annual"
.Move After:=wbDst.Sheets(lngDstIndex)
lngDstIndex = lngDstIndex + 1
End With
End With
End If
wbSrc.Close SaveChanges:=False
End If
strFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Function IfSheetExists(strName As String, Optional wb As Workbook) As Boolean
' checks for the existence of a worksheet named strName in the, optional, workbook wb
' if wb not stated checks in the active workbook
Dim ws As Worksheet
If wb Is Nothing Then
Set wb = ActiveWorkbook
End If
For Each ws In wb.Sheets
If ws.Name = strName Then
IfSheetExists = True
Exit For
End If
Next ws
End Function
Try this. The Master wb should be placed in a different folder than the one you store the Asset Files:
Sub Assets2Master()
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
xSheetName = "Annual"
xRgStr = "B1:GI100"
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
With xFileDlg
If .Show = -1 Then
xSelItem = .SelectedItems.item(1)
Set xWorkBook = ActiveWorkbook
Set xSheet = xWorkBook.Sheets("MASTER")
If xSheet Is Nothing Then
xWorkBook.Sheets.Add(After:=xWorkBook.Worksheets(xWorkBook.Worksheets.count)).Name = "MASTER"
Set xSheet = xWorkBook.Sheets("MASTER")
End If
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
If xFileName = "" Then Exit Sub
Do Until xFileName = ""
Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
xFileName = Dir()
xBook.Close
xBook.Name = xBook.Name & " - Annual"
Loop
End If
End With
Set xRg = xSheet.UsedRange
xRg.ClearFormats
xRg.UseStandardHeight = True
xRg.UseStandardWidth = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Stack Ranges
This is about what I thought your code was supposed to do. What you asked for is kind of illustrated with the commented block of code in the Do...Loop. By modifying the code in the Do...Loop, there are many possibilities of what you could achieve.
Option Explicit
Sub StackRanges()
' Source
Const sName As String = "Sheet1" ' "Annual"
Const sAddress As String = "B1:GI100"
' Destination
Const dName As String = "MASTER"
Const dCol As String = "A"
Application.ScreenUpdating = False
' Open the dialog to pick a folder.
Dim xFileDlg As FileDialog
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
Dim sFolderPath As Variant
With xFileDlg
.InitialFileName = ThisWorkbook.Path
If .Show = True Then
sFolderPath = .SelectedItems.Item(1)
Else
MsgBox "Canceled.", vbExclamation, "Assets2Master"
Exit Sub
End If
End With
' Write the name of the first file to the Source File Name variable.
Dim sfName As String: sfName = Dir(sFolderPath & "\*.xlsx")
' Validate first Source File Name.
If Len(sfName) = 0 Then Exit Sub ' no files found
' Create a reference to the Destination Workbook.
Dim dwb As Workbook: Set dwb = ThisWorkbook
' Write the name of the Destination Workbook
' to the Destination File Name variable.
Dim dfName As String: dfName = dwb.Name
' Attempt to create a reference to the Destination Worksheet.
Dim dws As Worksheet
On Error Resume Next
Set dws = dwb.Worksheets(dName)
On Error GoTo 0
' If the attempt was unsuccessful, add a new worksheet and do it now.
If dws Is Nothing Then
dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count)).Name = dName
Set dws = dwb.Worksheets(dName)
' Maybe add some headers... to the Destination Worksheet.
End If
' Create a reference to the (first) Destination Range.
Dim drg As Range: Set drg = dws.Range(sAddress)
Dim rCount As Long: rCount = drg.Rows.Count
Dim cCount As Long: cCount = drg.Columns.Count
Set drg = dws.Cells(dws.Rows.Count, dCol).End(xlUp) _
.Offset(1, 0).Resize(rCount, cCount)
' Declare additional variables for the following 'Do Loop'.
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
' Loop through the files in the folder...
Do Until Len(sfName) = 0
' Check if the Source File Name is different
' than the Destination File Name.
If StrComp(sfName, dfName, vbTextCompare) <> 0 Then
' Open and create a reference to the Source Workbook.
Set swb = Workbooks.Open(sFolderPath & "\" & sfName)
' Attempt to create a reference to the Source Worksheet.
Set sws = Nothing
On Error Resume Next
Set sws = swb.Worksheets(sName)
On Error GoTo 0
' Stack Ranges
' If the attempt was successful...
If Not sws Is Nothing Then
' Create a reference to the Source Range.
Set srg = sws.Range(sAddress)
' Copy the values from the Source to the Destination Range
' by assignment.
drg.Value = srg.Value
' Create a reference to the (next) Destination Range.
Set drg = drg.Offset(rCount)
End If
' ' Copy Worksheets (instead)
'
' ' If the attempt was successful...
' If Not sws Is Nothing Then
' sws.Copy After:=dwb.Sheets(dwb.Sheets.Count)
' ' Caution: Has to be less than 32 characters!
' ActiveSheet.Name = Left(sfName, Len(sfName) - 5) & " - " & sName
' End If
' Close the Source Workbook.
swb.Close SaveChanges:=False
End If
' Write the name of the next file to the Source File Name variable.
sfName = Dir
Loop
Application.ScreenUpdating = True
' Inform the user.
MsgBox "Data copied.", vbInformation, "Assets2Master"
End Sub