简体   繁体   中英

How to use a macro from an addin excel?

Im starting to program in excel VBA and what I want to do is:

1) When I open a new excel file (empty), I import the excel add-in

2) Then, I want to use the macro implemented on that add-in (in a module)

3) That add-in basically combines multiple excel worksheets (in the specified path), into a single one (the one where I ran the macro) Note: it works when not used as an add-in, that is, when used separately

4) When i run the following code in an empty excel file, it doesn't put the other worksheets in there. It just opens the first excel file it finds, and nothing more happens.

Do you know what is the error I'm doing? Thanks in advice :) .

Sub GetSheets()

Path = "C:specified path\"
Filename = Dir(Path & "*.xlsx")

Do While Filename <> ""

    Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

    For Each Sheet In ActiveWorkbook.Sheets
        Sheet.Copy After:=ThisWorkbook.Sheets(1)
    Next Sheet

    Workbooks(Filename).Close
    Filename = Dir()

Loop

End Sub

If you start the code from an Addin, ThisWorkbook refers to the Addin-file, but I guess you want to merge everything in your first ActiveWorkbook as destination.

Sub GetSheets()
    Dim fPath As String, fName As String
    Dim destWB As Workbook, currentWB As Workbook
    Dim i As Long

    Set destWB = ActiveWorkbook
    fPath = "C:\specified path\"
    fName = Dir(fPath & "*.xlsx")
    Do While fName <> ""
        Set currentWB = Workbooks.Open(Filename:=fPath & fName, ReadOnly:=True)
        For i = 1 To currentWB.Sheets.Count
            currentWB.Sheets(i).Copy After:=destWB.Sheets(destWB.Sheets.Count)
        Next i
        currentWB.Close SaveChanges:=False
        fName = Dir()
    Loop
End Sub

I suggest not use internal names like "Sheet" or "Filename" for your variables, so I changed their names.

If you always copy behind the first sheet, the sheet order is changed. So I changed it to append at the end instead.

As Sheets include chart sheets also, it is a better choice than Worksheet in this case. To loop over them, I suggest to use a counter, as ther is no Sheet object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM