尝试使用VBS运行Excel子版时未findmacros

我已经在网上find了下面的代码来尝试一个Excelmacros的自动化。

' Create a WshShell to get the current directory Dim WshShell Set WshShell = CreateObject("WScript.Shell") ' Create an Excel instance Dim myExcelWorker Set myExcelWorker = CreateObject("Excel.Application") Dim strSaveDefaultPath Dim strPath strSaveDefaultPath = myExcelWorker.DefaultFilePath strPath = WshShell.CurrentDirectory myExcelWorker.DefaultFilePath = strPath ' Open the Workbook specified on the command-line Dim oWorkBook Dim strWorkerWB strWorkerWB = strPath & "\Excel Report Creator.xlsm" Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB,0, true) ' Build the macro name with the full path to the workbook Dim strMacroName strMacroName = "'" & strPath & "\Excel Report Creator" & "!ReferenceSheet.CommandButton1_Click" on error resume next myExcelWorker.Run strMacroName if err.number <> 0 Then MsgBox "errerr: " & err.Description End If err.clear on error goto 0 oWorkBook.Save myExcelWorker.DefaultFilePath = strSaveDefaultPath ' Clean up and shut down Set oWorkBook = Nothing myExcelWorker.Quit Set myExcelWorker = Nothing Set WshShell = Nothing 

运行时收到以下错误。

 The macro may not be available in this workbook or all macros may be disabled. 

我的电子表格称为Excel Report Creator.xlsm,表格称为ReferenceSheet,子表格为CommandButton1_Click。 我在这里错过了什么? 可能是Excel中的设置?

谢谢,比尔

当工作簿名称有空格时,您需要用单引号将其包装。 如果工作簿打开,则不需要完整path:

 ' Build the macro name with the full path to the workbook Dim strMacroName strMacroName = "'Excel Report Creator.xlsm'" & _ "!ReferenceSheet.CommandButton1_Click" on error resume next myExcelWorker.Run strMacroName if err.number <> 0 Then MsgBox "errerr: " & err.Description End If err.clear on error goto 0 

并确保您打电话的Sub是Public