excel - 根据列表打开工作簿并运行特定宏

标签 excel vba

我正在尝试打开此范围内的所有工作簿并运行它们的宏。这个想法是打开第一个工作簿,运行宏,然后在继续下一个之前关闭它。宏的名称在所有工作簿中都相同。我正在运行代码,但出现(下标超出范围)错误。任何帮助将非常感激。

Sub files_export()

Dim wb As Workbook
Set wb = ThisWorkbook
Dim startsheet As Worksheet
Set startsheet = wb.Worksheets("Start")
    
Dim linkrange As Range
Set linkrange = startsheet.Range("C4:C21") 
    
    Dim y As String
    Dim c As Range
    
    For Each c In linkrange
        If c.Value <> "" Then
           y = c.Value
           Workbooks.Open (y)
           Workbooks(y).Application.Run ("macro1")
           Workbooks.close (y)
        End If
    Next c

End Sub

最佳答案

在另一个工作簿中运行宏

Option Explicit

Sub FilesExport()

    Const dName As String = "Start"
    Const FilePathsRangeAddress As String = "C4:C21"
    Const ModuleName As String = "" ' or e.g. "Module1"
    Const MacroName As String = "Macro1"

    Dim ModName As String: ModName = ModuleName
    If Len(ModName) > 0 Then ModName = ModName & "."

    Dim dwb As Workbook: Set dwb = ThisWorkbook
    Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
    
    Dim fprg As Range: Set fprg = dws.Range(FilePathsRangeAddress)
    
    Dim swb As Workbook
    Dim swbPath As String
    Dim sCell As Range
    Dim sMacroString As String
    
    For Each sCell In fprg.Cells
        swbPath = CStr(sCell.Value)
        If Len(swbPath) > 0 Then
           If Len(Dir(swbPath)) > 0 Then
               Set swb = Workbooks.Open(swbPath)
               sMacroString = "'" & swb.Name & "'!" & ModName & MacroName
               swb.Application.Run sMacroString
               swb.Close SaveChanges:=False ' maybe 'True' ?
           End If
        End If
    Next sCell

End Sub

关于excel - 根据列表打开工作簿并运行特定宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70541367/

相关文章:

excel - 编辑一段代码后需要帮助修复 vba 错误 '1004'

excel - 如何将句子转换为单个单词的列/行

excel - 如何使用多行自定义数字格式缩小列宽?

c# - Excel 对象有时不会被处理

excel - range.address 抛出上下文相关的错误

Excel - 返回列的第一个负数

excel - 当文档另存为 PDF 时,VBA 超链接不起作用

excel - 从 Excel 电子表格中的所有复选框中取消分配宏