excel - 尝试使用 VBS 运行 Excel 子程序时找不到宏

标签 excel vba vbscript

我在网上找到了以下代码来尝试自动化 Excel 宏。

 ' 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 中的设置?

谢谢, 比尔

最佳答案

当工作簿名称包含空格时,您需要将其用单引号引起来。如果工作簿打开,则不需要完整路径:

' 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

关于excel - 尝试使用 VBS 运行 Excel 子程序时找不到宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703357/

相关文章:

VBA 用户定义类型未定义(仅有时)

arrays - 使用数组和循环删除字符实例

excel - 使用通配符条件比较两个字符串

vbscript - msxml3.dll 访问被拒绝

excel - 使用 VBScript 打开 Excel 并运行宏

javascript - 将 JavaScript 代码转换为 VBScript 代码?

excel - 如何在 Excel 2013 中使用 Web 服务

excel - VBA for Excel : Server Data Not Updating

javascript - Excel 就像在 javascript 中建立索引

excel - 将一列与另一列值相乘