I need a macro that will copy tabs from all the files in a folder and combine them into one workbook. I have a current code which will pull the tabs, but they come back blank. I need all the data from the original files to be combined into one file. Is anyone able to help me fix this issue? Thank you in advance.
Sub CreateSheet(worksheetname)
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = worksheetname
End With
End Sub
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
' Insert your code here.
' The following line shows how to reference a sheet within
' the loop by displaying the worksheet name in a dialog box.
CreateSheet (ActiveWorkbook.Worksheets(I).Name)
Next I
End Sub
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
Call WorksheetLoop
'Change First Worksheet's Background Fill Blue
'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Replace your WorksheetLoop procedure with the code below. This will copy each sheet from the referenced (OpenedBook) workbook to ThisWorkbook.
Sub WorksheetLoop(OpenedBook As Workbook)
Dim wrksht As Worksheet
With ThisWorkbook
For Each wrksht In OpenedBook.Worksheets
wrksht.Copy Before:=.Worksheets(.Worksheets.Count)
Next wrksht
End With
End Sub
Change this line of code in the LoopAllExcelFilesInFolder procedure:
Call WorksheetLoop
to
WorksheetLoop wb
If the workbooks you're opening contain code in the open event you may need to add (I know there's a better way than this and I just can't think of it at the moment):
Application.EnableEvents = False
Set wb = Workbooks.Open(Filename:=myPath & myFile)
Application.EnableEvents = True
I don't think you can create a new sheet with a custom name, just the default name. But you can immediately rename it.
Try this:
With ThisWorkbook
set NewSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
NewSheet.Name = worksheetname
End With
It is possible to set the parameters in the sub procedure and use the copy command.
Sub WorksheetLoop(WB As Workbook)
Dim WS_Count As Integer
Dim I As Integer
Dim myWB As Workbook
Set myWB = ThisWorkbook
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = WB.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
' Insert your code here.
' The following line shows how to reference a sheet within
' the loop by displaying the worksheet name in a dialog box.
'CreateSheet (ActiveWorkbook.Worksheets(I).Name)
WB.Worksheets(I).Copy after:=myWB.Sheets(myWB.Sheets.Count)
Next I
End Sub
Sub LoopAllExcelFilesInFolder()
Dim WB As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set WB = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
WorksheetLoop WB
'Change First Worksheet's Background Fill Blue
'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'Save and Close Workbook
WB.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Related
Hi i have this code that counts the number of time "T" appears in the various workbooks where each workbook have around 10-12 sheets. the main objective is to have the final workbook get the the total number of times T appeared as it loops through the file.
Private Sub CommandButton3_Click()
Dim ws As Worksheet
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim x As Integer
Dim wash_count As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
For Each ws In wb.Sheets
If ws.Name <> "Summary" Then
For x = 5 To 74
If StrConv(ws.Cells(x, 2).Value, vbProperCase) = "Wash" And StrConv(ws.Cells(x, 4).Value, vbProperCase) = "T" Then 'added the StrConv to make sure you don't loose a case just because it was written in capital or lowercase letters
wash_count = wash_count + 1
End If
Next x
End If
Next ws
Sheets("Summary").Range("D6") = wash_count
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
The problem now is that the previous workbooks with the sheets also named "Summary" gets the counter input inside it too.
right now the code gets the final count in the last workbook, but how do i avoid having it appear in the summary pages in the previous workbooks, i want to direct all the counts only to the final workbook.
Thanks in advance
You can do something like this:
Dim ColFiles As New Collection, i As Long
'...
'...
'...
'collect the files first
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
ColFiles.Add myPath & myFile
myFile = Dir()
Loop
'now loop over the collection
For i = 1 To ColFiles.Count
Set wb = Workbooks.Open(ColFiles(i))
'count things in wb
'is this the last file?
If i = ColFiles.Count Then
wb.Sheets("Summary").Range("D6") = wash_count
wb.Close True 'save
Else
wb.Close False 'no save
End If
Next i
I'm new to VBA. I've been using for loop to add counts to my summary page, but as it loops through the multiple workbooks, the summary page keeps increasing as it adds up the value of the previous workbook too.
How do I specify the counter to just count and add into their specific summary page?
E.g. first workbook summary page count is 10, the next workbook workbook will be 10+ that workbook's count. Thanks in advance!
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim x As Integer
Dim wash_count As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
For Each ws In wb.Sheets
If ws.Name <> "Summary" Then
For x = 5 To 74
If ws.Cells(x, 2).Value = "Wash" And (ws.Cells(x, 4).Value = "T") Then
wash_count = wash_count + 1
End If
Next x
End If
Next ws
wb.Sheets("Summary").Range("D6") = wash_count
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
You're not resetting your counter:
'...
wb.Sheets("Summary").Range("D6") = wash_count
wash_count = 0 '<< reset for next workbook
I'm trying to save time in looking for excel files without a specific sheet named "RUNREADY" in a large directory of nested folders and excel files. This workbook without the worksheet would ideally be listed in a master excel file higher up in the directory or just have its name changed to end in a '(1)' or '(0)' depending on if it has the sheet or not.
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue
'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
Dim ws As Worksheet
Dim rr As Integer
Dim cel As Range
rr = 0
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "RUNREADY" Then
rr = rr + 1
Else
rr = 0
End If
Next ws
If rr = 1 Then
[RUNREADY.xlsm] Sheet1!cel.Value = ActiveWorkbook.FullName
[RUNREADY.xlsm] Sheet1!cel.Offset(1, 0)
End If
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I looked around for some sort of guidance and found this piece of code that searches through a file. I tried to write something that would write to a named excel file. my portion is spaced off in the middle of everything Running this i get an error at the first square bracket in my portion of code.
I have a Master Workbook with several labelled sheets. I am trying to update sheets in this workbooks named: 949, div and active pl.
The data for each of these 3 sheets would be pulled from 3 child workbooks, named accordingly as 949.xlsx, div.xlsx and activepl.xlsx. These workbooks have only 1 sheet in each of them.
How do I clear existing data except the header row then copy all the data from each of the child workbooks (disregarding the first row which is the header), into the respectively named sheets in the Master Workbook?
The macro I have so far:
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Try
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim vName As Variant, vDB As Variant
Dim Master As Workbook, Target As Range
Dim i As Integer
Set Master = ThisWorkbook
vName = Array("949", "div", "activepl")
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
For i = 0 To 2
If InStr(myFile, vName(i)) Then
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
vDB = wb.ActiveSheet.UsedRange.Offset(1)
Master.Sheets(vName(i)).UsedRange.Offset(1).Clear '<~~ Clear cells except head
Set Target = Master.Sheets(vName(i)).Range("b" & Rows.Count).End(xlUp)(2) '<~~ column b
Target.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End If
Next i
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
You can change the position by giving the condition according to the sheet name.
If vName(i) = "activepl" Then
Master.Sheets(vName(i)).UsedRange.Offset(1, 1).Clear '<~~ Clear cells except head
Set Target = Master.Sheets(vName(i)).Range("b" & Rows.Count).End(xlUp)(2) '<~~ column b
Else
Master.Sheets(vName(i)).UsedRange.Offset(1).Clear '<~~ Clear cells except head
Set Target = Master.Sheets(vName(i)).Range("a" & Rows.Count).End(xlUp)(2) '<~~ column b
End If
Edition
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim vName As Variant, vDB As Variant
Dim Master As Workbook, Target As Range
Dim i As Integer
Set Master = ThisWorkbook
vName = Array("949", "div", "activepl")
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
For i = 0 To 2
If InStr(myFile, vName(i)) Then
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
vDB = wb.ActiveSheet.UsedRange.Offset(1)
If vName(i) = "activepl" Then
Master.Sheets(vName(i)).UsedRange.Offset(1, 1).Clear '<~~ Clear cells except head
Set Target = Master.Sheets(vName(i)).Range("b" & Rows.Count).End(xlUp)(2) '<~~ column b
Else
Master.Sheets(vName(i)).UsedRange.Offset(1).Clear '<~~ Clear cells except head
Set Target = Master.Sheets(vName(i)).Range("a" & Rows.Count).End(xlUp)(2) '<~~ column b
End If
Target.Resize(UBound(vDB, 1), UBound(vDB, 2)) = vDB
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End If
Next i
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Here is my working code, I just want user to prompt for tab name, so that user can pick which tab to delete:
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Change First Worksheet's Background Fill Blue
'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
wb.Worksheets(2).Delete
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Add these variables (or similar) to the top of your code.
Dim DelSheet as string
Dim sht as worksheet
Get the sheet name - this is an example, you can get it from the user however you want
DelSheet = InputBox(Prompt:="Enter the name of the sheet to delete")
Modify this portion of your code, above. Leave the rest as is, since it seems to be working ok.
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'this loop isn't particularly efficient, but it prevents attempting
'deletion of the sheet if that sheet doesn't exist in the wb
'you could wrap the code in an "On Error..." block instead
for each sht in wb.sheets
if sht.name = DelSheet then
wb.Worksheets(DelSheet).Delete
endif
next
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
FreeMan's answer one step further (with multiple sheets to be deleted).
New variables
Dim DelSheets() As String 'array
Dim intDelSheetCount As Integer
Dim DelSht As Variant
New loop for user promt
'ask user multiple times, which sheets he wants to delete
Do
ReDim Preserve DelSheets(intDelSheetCount)
DelSheets(intDelSheetCount) = InputBox(Prompt:="Enter the name of the sheet to delete")
intMsgBoxAnswer = MsgBox("Do you want to type more sheets to be deleted?", vbYesNo)
intDelSheetCount = intDelSheetCount + 1
Loop While intMsgBoxAnswer = 6 'while the answer is YES
Deletion loop
For Each sht In wb.Sheets
For Each DelSht In DelSheets
If sht.Name = DelSht Then
DelSht.Delete
End If
Next DelSht
Next
Additional settings
To get rid of the Excel popup question, if you are super sure if you want to delete the sheet, you can use Application.DisplayAlerts = False at the beginning of the sub.