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