【问题标题】:How can I open multiple Excel files and execute a contained macro on each?如何打开多个 Excel 文件并在每个文件上执行包含的宏?
【发布时间】:2016-03-03 14:31:53
【问题描述】:

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

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

我该怎么办?

【问题讨论】:

标签: excel vba macros


【解决方案1】:

试试这样的。我希望您可以研究如何打开 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 编写的一些代码,因此无法保证它会起作用,我也没有时间对其进行测试。但是,如果没有,它会给你一个很好的开始。

编辑添加:你可以

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-17
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2021-11-17
    • 2013-08-24
    相关资源
    最近更新 更多