I am trying to save Excel diagrams as images.
With the whole code I call several workbooks, lookup all worksheets and save all diagrams.
The following code works with Excel 2007 and 2010 (but there is a horizontal and vertical line visible because of the + 4). If I change the
Round(shp.Width + 4, 0) to
Round(shp.Width, 0) I get the following error in 2010 (but not in 2007):
Run-Time error ‘-2147467259 (80004005)’:
The specified dimension is not valid for the current chart type.
Dim shp As Shape Dim sht As Worksheet Set sht = Application.ActiveWorkbook.Sheets(shtName) Set shp = sht.Shapes(chrtName) shp.CopyPicture xlScreen, xlBitmap Dim objChart As ChartObject Set objChart = sht.ChartObjects.Add(200, 200, Round(shp.Width + 4, 0), Round(shp.Height + 4, 0)) objChart.Activate ActiveChart.Paste ActiveChart.Export Filename:=fullPath, Filtername:=Right(fullPath, 3) objChart.Delete
How I can avoid using the +4?
I found the following:
“The problem occurs whenever the default chart type is set to other chart types than the ones you are trying to create. For an example, if you try to create line chart and if the default chart in Excel is OHLC (Candlestick Stock Chart) then Excel will be fast to complain “The specified dimension is not valid for the current chart type”. The same occurs even if you try to create charts from VB.NET. Hence, first of all change the default chart type to some basic chart types like Line charts. The problem will be solved.”
How can I do this with VBA?
Set objChart = Worksheet.Shapes.AddChart2().Chart.Parent
Set objChart = Worksheet.ChartObjects.Add()
The former function allows you to specify a basic chart type in the second argument.
Long time no answer.
You need to do two things. First, make sure no data is selected, or Excel may try to put it into the chart you’re creating.
Insert this block
Dim rngTmp as range If Typename(Selection) = "Range" then Set rngTmp = selection End If With ActiveSheet .Range("A1").Offset(.Rows.Count - 1).Select End With
before the line
Set objChart = sht.ChartObjects.Add(...)
and insert the following after the above line
ObjChart.Chart.ChartType = xlLine ' or another "safe" chart type If Not rngTmp is Nothing then rngTmp.select End If
Strictly speaking, if you are not adding data to the chart, you don’t need to change the chart type, but for the sake of OCD, it’s better to be complete.
I got the same exception. I traced the problem to the save path.
If the save path is wrong, or the specified path does not exist, then this exception will be raised. Check to make sure that the path exists.