title: Excel VBA Optimization
body: <p>I was asked by a user to run a macro from within an Excel book they created in order to automate a process. I call the macro from Java via cscript. I am no VBA programmer by any stretch of the imagination, but the code is inefficient and is simple copy/paste over and over. </p>
  
  <p>When I run the macro from Java I get the following error:</p>
  
  <p>Run-Time Error '1004':
  CopyPicture method of range class failed</p>
  
  <p>This error does not happen when I enter the workbook and manually click the button which launches this macro. </p>
  
  <p>I keep reading how using .Activate/Selection/.Select/etc can really slow down the code and cause this type of issue.</p>
  
  <p>Here is a code block that is used continually (instead of within a procedure/function call). It keeps throwing the error on the "Selection.CopyPicture" line. </p>
  
  <p>Any aid in optimizing this block would be appreciated.</p>
  
  <pre><code> ActiveSheet.ChartObjects("Chart 9").Activate
   ActiveChart.Pictures.Delete
   Range("InvGrid").Select
   Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
  
   ActiveSheet.ChartObjects("Chart 9").Activate
   ActiveChart.ChartArea.Select
   ActiveChart.Paste
   Application.CutCopyMode = False
   ActiveSheet.ChartObjects("Chart 9").Activate
   ActiveChart.ChartArea.Select
   ActiveChart.Export "C:\ABC.gif", "GIF", False
  </code></pre>
  
  <p>VBS launched from Java via csript</p>
  
  <pre><code> Dim xlsWorkbook
   Dim objExcel
   Set objExcel = CreateObject(\"Excel.Application\")
   objExcel.Application.DisplayAlerts = False
   Set xlsWorkbook = objExcel.WorkBooks.Open(\"" + xlsmFilepath + "\", 3)
   objExcel.Application.Run(xlsWorkbook.Name &amp; \"!ExportCharts\")
   xlsWorkbook.Save
   xlsWorkbook.Close
   objExcel.Quit
  </code></pre>