title: Calling Excel macros/Excel Solver from Python over com
body: <p>I have a macro inside a 2007 xlsm file that, when called, creates a solver configuration (target, constraints, ...) and performs the solve without any user interaction. When run manually from Excel, this works fine.</p>
  
  <p>I now want to script this from Python over com. However, when the Python code calls the solver macro:</p>
  
  <pre><code>app.Run("runSolver()")
  </code></pre>
  
  <p>It fails with:</p>
  
  <blockquote>
    <p>foobar.xlsm failed to solve, error message: Error in model. Please
    verify that all cells and constraints are valid.</p>
  </blockquote>
  
  <p>If I set a breakpoint in my Python environment at the call to <code>Run()</code> and then run the macro manually from Excel, it works fine, so the solver configuration can't be wrong.</p>
  
  <p>The error message is listed <a href="http://www.solver.com/suppstdmsgresult7.htm" rel="nofollow">on the solver website</a> but I don't think it applies as the sheet solves fine manually.</p>
  
  <p><a href="http://peltiertech.com/Excel/SolverVBA.html" rel="nofollow">This page suggests</a> that the solver environment is not yet set up when calling through com.  However, adding </p>
  
  <pre><code>Application.Run "Solver.xla!Solver.Solver2.Auto_open"
  </code></pre>
  
  <p>As the first line of my solver macro results in the more generic:</p>
  
  <pre><code>  File "c:\python26\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x6.py", line 35061, in Run
      , Arg26, Arg27, Arg28, Arg29, Arg30
    File "c:\python26\lib\site-packages\win32com\client\__init__.py", line 456, in _ApplyTypes_
          self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
  com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None)
  </code></pre>
  
  <p>So what is the right thing to do?</p>
  
  <hr>
  
  <p><strong>Edit:</strong></p>
  
  <p>I isolated it down to a reproducable test case:</p>
  
  <p>Python code:</p>
  
  <pre><code>from win32com.client import Dispatch
  if __name__ == '__main__':
      app = Dispatch("Excel.Application")
      app.Visible = True
      app.Workbooks.Open(r'C:\path\to\testsolver.xlsm')
      app.Run("runsolver()")
  </code></pre>
  
  <p>Excel file: <a href="http://dl.dropbox.com/u/3142953/testsolver.xlsm" rel="nofollow">http://dl.dropbox.com/u/3142953/testsolver.xlsm</a> (you can open it with Macros disabled and inspect the simple sub in <code>module1</code> to verify it's safe).</p>