如何从Ruby运行Excel宏?
问题
我有这个十年前的Excel工作簿,里面有大量的VBA代码,其中一些我需要更新。 所以我有一个在Ruby中编写unit testing的疯狂想法……
题
如何从Ruby调用Excel宏?
到目前为止我有什么
我有
- 一个名为“C:\ temp \ Test.xlsm”的Excel工作簿
- 用一张名为“Sheet1”的表格和
- 单元格“A1”。
此外,这个Excel工作簿
- 包含一个名为“Module1”的模块
- 用一个名为
WriteToA1()
的宏和 - 另一个名为
ClearA1()
宏
另外,我有一个看起来像这样的Ruby脚本:
require 'test/unit' require 'win32ole' class TestDemo < Test::Unit::TestCase def testExcelMacro # Arrange excel = WIN32OLE.new("Excel.Application") excel.Visible = true excel.Workbooks.Open('C:\temp\Test.xlsm') # Act excel.run "Sheet1!WriteToA1" # Assert worksheet = excel.Workbooks.ActiveWorkbook assert_equal("blah", worksheet.Range("A1").Value) excel.Quit end end
例外
我得到了这个例外
WIN32OLERuntimeError: (in OLE method `run': ) OLE error code:800A03EC in Microsoft Excel Cannot run the macro 'Sheet1!WriteToA1'. The macro may not be available in this workbook or all macros may be disabled. HRESULT error code:0x80020009 Exception occurred.
我已经在Excel中启用了所有宏,如此处所述。
Excel正在启动,“Test.xlsm”已打开。 这条线肯定有问题:
excel.run "Sheet1!WriteToA1"
我也试过这个:
excel.run "Sheet1!Module1.WriteToA1"
您需要提供的所有OLE模块都是宏名称
excel.run('WriteToA1')
另请注意,如果要运行带有争论的宏,请使用:
excel.run('MarcoWithArgs', "Arg")