【发布时间】:2012-06-09 19:32:17
【问题描述】:
问题
我有这本已有十多年历史的 Excel 工作簿,其中包含大量 VBA 代码行,其中一些我必须更新。所以我萌生了用 Ruby 编写单元测试的疯狂想法……
问题
如何从 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.
我已按照here 所述启用 Excel 中的所有宏。
Excel 正在启动,“Test.xlsm”已打开。这条线一定有问题:
excel.run "Sheet1!WriteToA1"
我也试过这个:
excel.run "Sheet1!Module1.WriteToA1"
【问题讨论】:
-
试试这个
excel.run "Test!WriteToA1"
标签: ruby unit-testing excel vba