As the title suggests, this code fails on the line
Sheet.Copy After:=ThisWorkbook.Sheets(1) with runtime error 1004
Why would this run when added as a module but not when saved as an add-in?
Here’s the code:
Dim FolderPath As String Dim Filename As String Dim Sheet As Worksheet Application.ScreenUpdating = False FolderPath = GetFolder() & "\" Filename = Dir(FolderPath & "*.xls*") Do While Filename <> "" Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True For Each Sheet In ActiveWorkbook.Sheets Sheet.Copy After:=ThisWorkbook.Sheets(1) Next Sheet Workbooks(Filename).Close Filename = Dir() Loop Application.ScreenUpdating = True End Sub
As @BruceWayne suggested is a problem with deciding the correct workbook. As an
ThisWorkbook will be the
AddIn workbook, while
ActiveWorkbook (before opening others), will be the workbook you are running your
ActiveWorkbook in your scenario won’t work, because you would just copy the sheets from the newly open workbook, to the same.
Is a good idea to declare variables to hold this informations, then you can open as many workbooks as you want, and from where you want.
Application.ScreenUpdating = False Dim wbDst As Workbook: Set wbDst = ActiveWorkbook 'Can also use Worbooks("book name here") Dim wbSrc As Workbook Dim Sht As Worksheet Dim FolderPath As String: FolderPath = GetFolder() & "\" Dim FileName As String: FileName = Dir(FolderPath & "*.xls*") Do While FileName <> "" Set wbSrc = Workbooks.Open(FileName:=FolderPath & FileName, ReadOnly:=True) For Each Sht In wbSrc.Worksheets Sht.Copy After:=wbDst.Sheets(1) Next Sht wbSrc.Close FileName = Dir() Loop Application.ScreenUpdating = True