设置宽度和高度ChartObject
或它Shape
不这样做。它们似乎都只是嵌入图表的那个白色矩形的内部部分。ChartArea
似乎也不是我感兴趣的对象。
我希望以下示例中的导出文件具有 800x600 的尺寸(我并不是说重新缩放导出的图像或反复试验,直到尺寸意外适合)。图表周围一定有一些我忽略的对象。
Sub mwe()
Dim filepath As String
Dim sheet As Worksheet
Dim cObj As ChartObject
Dim c As Chart
Dim cShape As Shape
Dim cArea As chartArea
filepath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\"))
Set sheet = ActiveSheet
Set cObj = sheet.ChartObjects(1)
Set c = cObj.chart
Set cShape = sheet.Shapes(cObj.Name)
Set cArea = c.chartArea
cObj.Width = 800
cObj.Height = 400
MsgBox cArea.Width & " x " & cArea.Height '793x393
c.Export filepath & "test1.png" '1067x534, this is also the size on screen
cShape.Width = 800
cShape.Height = 400
MsgBox cArea.Width & " x " & cArea.Height '794x393
c.Export filepath & "test2.png" '1068x534, this is also the size on screen
End Sub
更新:
事实证明,ChartObject
和Shape
属于相同的Chart
已经有Worksheet
父级,但是宽度和高度不是以像素为单位,而是以点为单位,其中 1 点 = 1/72 英寸,并且大多数情况下,Windows 似乎假设每个 96 像素英寸。
感谢史蒂夫的评论,我现在正在使用以下内容,这是非常可靠的。
在导出时未激活的AChartObject
似乎会生成一个宽度和高度比应有的高 1 的文件。
px2ptH
还有待找出如何px2ptV
自动确定这些因素。
Sub mwe()
Dim filepath As String
Dim sheet As Worksheet
Dim cObj As ChartObject
Dim c As Chart
Dim px2ptH As Double: px2ptH = 72 / 96
Dim px2ptV As Double: px2ptV = 72 / 96
Dim w As Double: w = 800 * px2ptH
Dim h As Double: h = 400 * px2ptV
filepath = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, "\"))
Set sheet = ActiveSheet
Set cObj = sheet.ChartObjects(1)
Set c = cObj.Chart
'otherwise image size may deviate by 1x1
cObj.Activate
cObj.Width = w
cObj.Height = h
c.Export filepath & "test.png"
End Sub