Home » excel » excel – Code runs when copy/pasted as macro, but not when saved as add-in

excel – Code runs when copy/pasted as macro, but not when saved as add-in

Posted by: admin May 14, 2020 Leave a comment


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
 Filename = Dir()

Application.ScreenUpdating = True
End Sub
How to&Answers:

As @BruceWayne suggested is a problem with deciding the correct workbook. As an AddIn, ThisWorkbook will be the AddIn workbook, while ActiveWorkbook (before opening others), will be the workbook you are running your AddIn into.

Simply replacing Thisworkbook with 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.

See below:

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

    FileName = Dir()

Application.ScreenUpdating = True