how do i open ALL the excel files one by one and run a macro

前端 未结 2 481
面向向阳花
面向向阳花 2020-12-03 19:24

I need to write a macro in VBA that will open every file in a given directory one by one and run a macro on them.

so far i have something like

for i         


        
相关标签:
2条回答
  • 2020-12-03 19:28

    By calling the Dir() function with an appropriate filter, such as "c:\folder\*.xls", you start enumeration and get the first file name.
    After that, repeatedly calling the Dir() function without any parameters, you will get all *.xls file names, one for each call.

    You open a workbook by calling Workbooks.Open(full_path). This gives you a Workbook object, against which you can run a macro.

    The .Close() method of this Workbook object closes the workbook. You can use .Close(SaveChanges:=True) to save changes, .Close(SaveChanges:=False) to discard changes, or omit the parameter to have the user decide.

    0 讨论(0)
  • 2020-12-03 19:32

    Here's the easy VBA object way to do it:

    Dim fs As FileSearch
    Dim i As Integer
    Dim wbk As Workbook
    
    Set fs = Application.FileSearch
    
    With fs
        .LookIn = ThisWorkbook.Path
        .FileName = "*.xls"
        For i = 1 to .Execute()
            Set wbk = Workbooks.Open(.FoundFiles(i))
            ''//RUN MACRO HERE
            wbk.Close(SaveChanges:=True)
        Next i
    End With
    
    0 讨论(0)
提交回复
热议问题