Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run an Excel macro from Ruby?

Problem

I have this ten something year old Excel workbook with a gazillion lines of VBA code in it some of which I have to update. So I had this crazy idea of writing unit tests in Ruby...

Question

How can I call an Excel macro from Ruby?

What I have so far

I have

  • an Excel workbook called "C:\temp\Test.xlsm"
  • with an sheet called "Sheet1" and
  • a cell "A1".

Furthermore, this Excel workbook

  • contains a module called "Module1"
  • with a macro called WriteToA1() and
  • another macro called ClearA1()

Plus, I have a Ruby script looking like this:

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

Exception

I get this exception

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.

I have enabled all macros in Excel as described here.

Excel is being started, "Test.xlsm" is opened. Something must be wrong with the line:

excel.run "Sheet1!WriteToA1"

I have also tried this:

excel.run "Sheet1!Module1.WriteToA1"
like image 808
Lernkurve Avatar asked Jan 23 '26 13:01

Lernkurve


1 Answers

All you need to provide the OLE module is the macro name

excel.run('WriteToA1')

Also note, if you want to run a macro with an arguement, you use:

excel.run('MarcoWithArgs', "Arg")
like image 124
Pynner Avatar answered Jan 25 '26 03:01

Pynner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!