Excel VBA Optimization

自作多情 提交于 2020-01-04 06:27:49

问题


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.

When I run the macro from Java I get the following error:

Run-Time Error '1004': CopyPicture method of range class failed

This error does not happen when I enter the workbook and manually click the button which launches this macro.

I keep reading how using .Activate/Selection/.Select/etc can really slow down the code and cause this type of issue.

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.

Any aid in optimizing this block would be appreciated.

 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

VBS launched from Java via csript

 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 & \"!ExportCharts\")
 xlsWorkbook.Save
 xlsWorkbook.Close
 objExcel.Quit

回答1:


Something like this maybe:

Dim cht As Chart
Set cht = ActiveSheet.ChartObjects("Chart 9").Chart
ActiveSheet.Range("InvGrid").CopyPicture Appearance:=xlScreen, Format:=xlPicture
With cht
    If .Pictures.Count > 0 Then .Pictures.Delete
    .Paste
    .Export "C:\ABC.gif", "GIF", False
End With


来源:https://stackoverflow.com/questions/15911957/excel-vba-optimization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!