从命令行使用VBScript从Excel外部运行Excel宏

mut*_*y91 30 vbscript excel command-line vba

我正在尝试从Excel文件外部运行Excel宏.我目前正在使用从命令行运行的".vbs"文件,但它一直告诉我无法找到宏.这是我正在尝试使用的脚本

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")

objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"

objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close


objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试访问的宏:

Sub TestMacro()
'first set a string which contains the path to the file you want to create.
'this example creates one and stores it in the root directory
MyFile = "C:\Users\username\Desktop\" & "TestResult.txt"
'set and open file for output
fnum = FreeFile()
Open MyFile For Output As fnum
'write project info and then a blank line. Note the comma is required
Write #fnum, "I wrote this"
Write #fnum,
'use Print when you want the string without quotation marks
Print #fnum, "I printed this"
Close #fnum
End Sub
Run Code Online (Sandbox Code Playgroud)

我尝试了位于的解决方案是否可以从外部命令在Excel中运行宏?到目前为止(并修改)但它似乎没有用.我一直收到错误`Microsoft Office Excel:无法找到宏'Macro.TestMacro'.

编辑:Excel 2003.

小智 34

好的,它实际上很简单.假设您的宏位于模块中,而不是在其中一个工作表中,则使用:

  objExcel.Application.Run "test.xls!dog" 
  'notice the format of 'workbook name'!macro
Run Code Online (Sandbox Code Playgroud)

对于带空格的文件名,请用引号括住文件名.

如果你把宏放在一张纸下,比如说sheet1,那么假设sheet1拥有它所具有的功能.

    objExcel.Application.Run "'test 2.xls'!sheet1.dog"
Run Code Online (Sandbox Code Playgroud)

注意:您不需要您一直使用的macro.testfunction表示法.


Sid*_*out 23

我想你是想这么做的?(经过试验和测试)

此代码将打开文件Test.xls并运行宏TestMacro,该宏将依次写入文本文件TestResult.txt

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit
Run Code Online (Sandbox Code Playgroud)


acc*_*ted 5

由于我杀死了一整天后都在寻找如何解决“未找到或禁用宏”错误的错误后,用义手解决了我的相关问题,因此在此发布了唯一对我有用的语法(application.run无效,无论如何我尝试过的

Set objExcel = CreateObject("Excel.Application")

' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"

' Only ran like this (from the Module1)

Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Run Code Online (Sandbox Code Playgroud)

Excel 2010,Win 7