如何打开多个Excel文件并在每个文件上执行包含的宏?

时间:2016-03-03 14:31:54

标签: excel vba macros

我希望打开多个Excel文件并在每个文件上运行相同的宏(包含在每个文件中)。

例如,我想自动打开h:\ dbs中的每个文件,并在每个文件中执行CmdUpdate_Click宏。

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情。我希望您可以研究如何打开Visual Basic编辑器并找出粘贴它的位置。

'Declare variables

Dim FolderObj, FSO, FileObj As Object
Dim FolderDialog As FileDialog

'Create and run dialog box object

Set FolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
    .ButtonName = "Select"
    .AllowMultiSelect = False
    .InitialFileName = "B:\BIM Projects\"
    .InitialView = msoFileDialogViewDetails

    'Check if user canceled dialog box
    'Exit if yes
    If .Show = -1 Then
        MsgBox "No Folder Selected"
        Exit Sub
    End If

End With

'Check if user canceled dialog box
'Exit if yes


'Create a File System Object to be the folder that was selected

Set FSO = CreateObject("scripting.filesystemobject")

Set FolderObj = FSO.getfolder(FolderLocation)


'For each obj in the selected folder
For Each FileObj In FolderObj.Files

    'Test if the file extension contains "xl" and make sure it's an Excel file before opening
    If InStr(1, Right(FileObj.Name, Len(FileObj.Name) - InStr(1, FileObj.Name, ".")), "xl") = 1 Then

        'Prevent the workbook from displaying
        ActiveWindow.Visible = False

        'Open the Workbook
        Workbooks.Open (FolderObj & "\" & FileObj.Name)

        'Run the Macro
        Application.Run "'" & FolderObj & "\" & FileObj.Name & "'!CmdUpdate_Click"

        'Save the Workbook
        Workbooks(FileObj.Name).Save

        'Close the Workbook
        Workbooks(FileObj.Name.Close

    End If

'Turn this back on
ActiveWindow.Visible = True
Next

我会提醒您,这是基于我为Word编写的一些代码,因此无法保证它能够正常工作,而且我没有时间对其进行测试。但是,如果它没有,它会给你一个很好的开始。

编辑添加:您可以