我正在尝试在几个相同的工作簿中运行一个宏,然后将这些工作簿的第一张表合并到一个新的工作簿中。合并部分正在通过互联网工作,但我似乎没有让“运行宏”部分失效。到目前为止,这是我的代码:
Sub MergeSelectedWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim SelectedFiles() As Variant
Dim NRow As Long
Dim FileName As String
Dim NFile As Long
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
FolderPath = "..."
ChDrive FolderPath
ChDir FolderPath
SelectedFiles = Application.GetOpenFilename( _
filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
NRow = 1
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
' Set FileName to be the current workbook file name to open.
FileName = SelectedFiles(NFile)
Set WorkBk = Workbooks.Open(FileName)
Run "Détaildesmlh_Bouton1_Cliquer" #this is what doesn't work
SummarySheet.Range("A" & NRow).Value = FileName
Set SourceRange = WorkBk.Worksheets(1).Range("A1:G19")
Set DestRange = SummarySheet.Range("B" & NRow)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
DestRange.Value = SourceRange.Value
NRow = NRow + DestRange.Rows.Count
WorkBk.Close savechanges:=True
Next NFile
SummarySheet.Columns.AutoFit
End Sub
我尝试了不同的方法来运行宏,我上面添加的代码返回错误,因为宏不存在或不活动。你有任何解决方法吗?我试过查看我在网上找到的解决方案,但是他们要么不使用其余的代码,要么看起来很复杂。
谢谢!
答案 0 :(得分:1)
Set WorkBk = Workbooks.Open(FileName)
Run "Détaildesmlh_Bouton1_Cliquer" #this is what doesn't work
上面的不起作用,因为语法不正确:)
试试这个。
Set WorkBk = Workbooks.Open(FileName)
Application.Run FileName &"!Détaildesmlh_Bouton1_Cliquer"
N.B。 - 你可能需要从FileName中删除UNC路径(如果它在那里)并且只传递工作簿名称(即 - MyBook.xlsm)