VBA Excel:指定的维度对当前图表类型无效
我试图用vba将excel图表保存为图像。在整个代码中,我会调用几个工作簿,查找所有工作表并保存所有图表。以下代码适用于Excel 2007和2010(但由于+ 4,存在水平线和垂直线)。如果我将Round(shp.Width + 4,0)更改为Round(shp.Width,0),我在2010年(但不是在2007年)中收到以下错误:VBA Excel:指定的维度对当前图表类型无效
运行时错误'-2147467259 80004005)': 指定的维度对当前的图表类型无效。
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
有人知道如何避免使用+4吗?
我发现了以下内容:
“每当默认图表类型设置为其他类型的图表比你要创建的那些出现问题举一个例子,如果你尝试创建线图,如果Excel中的默认图表是OHLC(Candlestick Stock Chart),那么Excel会很快抱怨“指定的维度对于当前图表类型无效”即使您尝试从VB.NET创建图表也是如此,因此,首先将默认图表类型更改为折线图等基本图表类型,问题将得到解决。“ http://www.excelbanter.com/showthread.php?t=204071
但我不知道如何用VBA做到这一点。
很久没有答案。
你需要做两件事。首先,确保没有选择数据,否则Excel可能会尝试将其放入您创建的图表中。
插入此块
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
行
Set objChart = sht.ChartObjects.Add(...)
,并插入上面一行
ObjChart.Chart.ChartType = xlLine ' or another "safe" chart type
If Not rngTmp is Nothing then
rngTmp.select
End If
严格地说后下面的,如果你不将数据添加到前图表,你不需要改变图表类型,但为了强迫症,最好是完整的。
使用
Set objChart = Worksheet.Shapes.AddChart2().Chart.Parent
代替
Set objChart = Worksheet.ChartObjects.Add()
前者功能允许您指定一个基本的图表类型中的第二个参数。
为了与Excel 2007和2010兼容,使用'AddChart()'代替'AddChart2()'。 – 2017-05-25 11:11:10
无心投票...对不起! – Hoakie 2015-05-13 20:35:59
@jon,你如何“选择”一个不存在的单元?行.Range(“A1”)。Offset(.Rows.Count + 1).Select在我的测试中抛出异常,这是合理的,因为row .Rows.Count + 1行不存在。 – OfficeAddinDev 2017-05-19 15:55:57
好点。我已将它更改为“ - 1”。 – 2017-05-25 11:09:06