2009-06-01

Getting Excel addins to work with Ruby

I was having difficulty with this until I came across this post by bbiker.  The problem is that when you open Excel with a program OLE link it has a different environment to that when you open manually.  Specifically addins might not work and need to be kicked.

I put it to work with the following function in the test code (this is non working code as it requires your own addin name) :

require 'win32ole'

class UpdateAddInFile

  def addin_installed?(ai)
    begin
      puts "Addins: #{ai}? =  #{@xl.AddIns(ai).Installed}"
      @xl.AddIns(ai).Installed=0
      @xl.AddIns(ai).Installed=1
    rescue
      puts "<><>Testing for adding #{ai} caused an exception."
    end
  end

  def initialize(thisFile)
    @xl = WIN32OLE.new('Excel.Application')
    @xl.Visible = true
    addin_installed?("Your Add-In")
    #Satisfying wait as Excel addins get installed
    dummy = @xl.workbooks.Add # Add a new work book
    dummy.Cells(1,1).value = "add in functions will now work"
  end

end

UpdateAddInFile.new('c:\\test.xls')

puts "Waiting for readline"
readline

1 comment:

Mitch said...

Thanks! You just saved me a bunch of stumbling around in PythonWin with this post.