从命令行使用VBScript从外部Excel运行Excel宏 [英] Run Excel Macro from Outside Excel Using VBScript From Command Line

查看:214
本文介绍了从命令行使用VBScript从外部Excel运行Excel宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel文件外部运行Excel宏。我正在使用从命令行运行的.vbs文件,但它不断告诉我无法找到宏。这是我试图使用的脚本

I'm trying to run an Excel macro from outside of the Excel file. I'm currently using a ".vbs" file run from the command line, but it keeps telling me the macro can't be found. Here is the script I'm trying to use

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

这里是我要访问的宏: p>

And here is the Macro I'm trying to access:

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

位于是否可以运行宏从外部命令的Excel?得到这个远(当然修改),但似乎不起作用。我继续收到错误'Microsoft Office Excel:找不到宏Macro.TestMacro。

I tried the solutions located at Is it possible to run a macro in Excel from external command? to get this far (and modified of course) but it didn't seem to work. I keep getting the error `Microsoft Office Excel: The macro 'Macro.TestMacro' cannot be found.

编辑:Excel 2003。

Excel 2003.

推荐答案

好的,其实很简单。假设您的宏位于模块中,而不是其中一个表单,则可以使用:

Ok, it's actually simple. Assuming that your macro is in a module,not in one of the sheets, you use:

  objExcel.Application.Run "test.xls!dog" 
  'notice the format of 'workbook name'!macro

一个带有空格的文件名,用引号括起文件名。

For a filename with spaces, encase the filename with quotes.

如果你把宏放在一张表单下,说sheet1,只是假设sheet1拥有这个功能。

If you've placed the macro under a sheet, say sheet1, just assume sheet1 owns the function, which it does.

    objExcel.Application.Run "'test 2.xls'!sheet1.dog"

注意:您不需要您一直在使用的macro.testfunction符号。

Notice: You don't need the macro.testfunction notation you've been using.

这篇关于从命令行使用VBScript从外部Excel运行Excel宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆