从外部VBScript错误运行Excelmacros

我有两个文件。

  1. example.wsf:一个自动化脚本
  2. example.xlsm:带有Macro的Excel模板,Macro包含一个API调用外部服务器来检索数据。

我正在尝试调用example.wsf中的macros。

example.wsf代码:

<package> <job id="example"> <script language="vbscript"> Set objApp = CreateObject("Excel.Application") Set objExcel = objApp.Workbooks.Open("example.xlsm",0,FALSE) objApp.Visible = True objApp.DisplayAlerts = False objApp.Run("RefreshData") msgbox "closing" objExcel.Close objApp.Quit Set objExcel = Nothing Set objApp = Nothing set objShell = Nothing </script> </job> </package> 

example.xlsm中的Excelmacros代码:

 Public Sub RefreshData() Dim API As New EXTERNAL_API Dim varResult As Variant Dim vSheet As String Dim LastRow, LastCol, vResult vSheet = "D" ActiveWorkbook.Sheets(vSheet).Select Range("A6").Select Selection.Copy Range(Selection, Selection.End(xlDown)).Select LastRow = ActiveWorkbook.Sheets(vSheet).Cells(8, 1).End(xlDown).Row LastCol = 18 API.ActivateAPI varResult = API.RunApplication("OfficeAPI", "application=excel,method=RefreshAll") MsgBox (varResult) End Sub 

如果在Excel工作簿中触发,macros本身运行良好。

但是,当从VBScript调用macros时,EXTERNAL_API无法执行,即下面的行不执行:

 varResult = API.RunApplication("OfficeAPI", "application=excel,method=RefreshAll") 

我怀疑这可能与早期绑定有关,但基本上不知道哪里出了问题。

看起来你几乎在那里。 只是一些格式问题。 见下面的代码片段。 请注意我对文件path的意见以及macros在excel文件中的位置。 请让我知道这对你有没有用。

 Set objApp = CreateObject("Excel.Application") Set objExcel = objApp.Workbooks.Open("example.xlsm", 0, False) ''make sure you have valid path, such as a full UNC path objApp.Visible = True objApp.DisplayAlerts = False objApp.Run "example.xlsm!RefreshData" ' this is if the Macro is in a Module. Use "example.xlsm!sheet1.RefreshData" if it's on ' sheet1, for example