I'm trying develop a macro that pulls in all sheets from all workbooks in a folder if that worksheet doesn't already exist in the master workbook. IE
Folder
|---Summary Sheet.xlsm
|---Sheet 1 date1.xlsx
|---Sheet 2 date2.xlsx
etc.
The macro opens the workbook, renames the sheet to the date off a cell, copies it across then closes it without saving/prompting. I can't seem to incorporate the name check correctly. I've looked over
Test or check if sheet exists
Excel VBA If WorkSheet("wsName") Exists
But lack the experience to properly translate the concepts across.
This is the code so far. Running now throws a runtime error 438 with
sheetToFind = ThisWorkbook.Sheets(1)
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Dim sheetToFind As String
Dim sheetExists As Boolean
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = Environ("userprofile") & "\Folder\"
Filename = Dir(FolderPath & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
sheetExists = False
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Name = Sheet.Range("C4")
sheetToFind = ThisWorkbook.Sheets(1)
If sheetToFind = Sheet.Name Then
sheetExists = True
End If
If sheetExists = False Then
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close False
Filename = Dir()
End If
Next Sheet
Loop
Application.ScreenUpdating = True
End Sub
ThisWorkbook.Sheets(1)
is an object and needsSet
. =>Set sheetToFind = ThisWorkbook.Sheets(1)
... but alsosheetToFind = Sheet.Name
would fail assheetToFind
is an object which cannot be compared like that...sheetToFind.Name = Sheet.Name
should do the trick there ;) – Dirk ReichelDo.. sheetToFind.Name = Sheet.Name For Each Sheet....
I get an invalid qualifier error. Have I left something out or put it in the wrong place? Can I search all sheet names to compare the renamed sheet to? – MashicalsheetToFind = ThisWorkbook.Sheets(1)
tosheetToFind = ThisWorkbook.Sheets(1).Name
and check if it is doing what you want – Dirk Reichel