【发布时间】:2019-02-15 23:19:23
【问题描述】:
我最近从 2010 年迁移到 Excel 2016,我从同事那里继承的一张工作表已停止工作。我正在学习 VBA,但如果我在运行以下代码时遇到运行时错误,我将不胜感激。
我相信它是由声明变量的方式造成的(或者在这种情况下似乎不是)。该函数采用覆盖图表的范围。然后它将图表导出为 .png 图像。我不明白的另一件事是为什么它在 Excel 2010 中运行良好但在 2016 中运行良好?
错误 424 - 需要对象:
With .Pictures(1)
代码:
Sub createPNG(sheetName As String, rangeName As String, fileName As String)
Dim vFilePath As Variant
Dim rSelection As Range
Dim sDefaultName As String
Sheets(sheetName).Range(rangeName).Select
Set rSelection = Selection
vFilePath = "Z:\marginsOutput\Charts\" & fileName & ".png"
'-- copy selected range as picture (not as bitmap)
rSelection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
'--Create an empty chart, slightly larger than exact size of range copied
With Sheets(sheetName).ChartObjects.Add( _
Left:=rSelection.Left, Top:=rSelection.Top, _
Width:=rSelection.Width + 2, Height:=rSelection.Height + 2)
With .Chart
' clean up chart
.ChartArea.Format.Line.Visible = msoFalse
' paste and position picture
.Paste
With .Pictures(1)
.Left = .Left + 2
.Top = .Top + 2
End With
' export
.Export CStr(vFilePath)
End With
' remove no-longer-needed chart
.Delete
End With
End Sub
【问题讨论】:
-
哪行代码中断了?您可以通过点击运行时错误弹出窗口中的调试按钮来判断。
-
嗨,David,这是 With .Pictures(1) 行
-
查看
With语句的嵌套。由于三重嵌套,您的对象无效。您应该将Sheets(SheetName).Pictures(1)作为您的对象。 -
我什至不确定您是否需要最后一个
With语句中的代码?尝试注释掉给你错误的行 + 以下 3 行,看看你是否仍然得到想要的结果。 -
谢谢大家,实际上注释掉代码块会导致函数导出空白图像。 @Darrell,修改该行会给我一个“无法获取 Worksheet 类的图片属性”错误