【问题标题】:How do I run an Excel macro from Ruby?如何从 Ruby 运行 Excel 宏?
【发布时间】: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


【解决方案1】:

您只需提供 OLE 模块的宏名称即可

excel.run('WriteToA1')

另请注意,如果您想运行带有争论的宏,请使用:

excel.run('MarcoWithArgs', "Arg")

【讨论】:

  • 我们是否有机会使用 win32ole 编写/修改宏?或者直接在 ruby​​ 中处理?一些想要的库,我只能在“VBA Studio -> Reference”中找到,我更喜欢动态生成的marco,任何线索都可以接受:),@Lernkurve
  • 哇,我也在找这个解决方案,我需要从 ruby​​ 编写/修改宏。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
相关资源
最近更新 更多