How do I set the width and height of the graph in pixels?
Setting the width and height ChartObject
or it Shape
doesn't. They both seem to be just some of the inside of this white rectangle, which is an inline diagram. Also ChartArea
doesn't seem to be the object I'm interested in.
I want the exported file in the following example to be 800x600 (and I don't mean scaling the exported image or trial and error until the size matches by chance). There must be some object around the plot that I missed.
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
Update:
It turns out that ChartObject
and Shape
belonging to the same Chart
already have ChartObject
Worksheet
as a parent, but the width and height in pixels is not indicated, and the points, where 1 point = 1/72 of an inch, and in most cases seem to assume Windows 96 ppi.
Thanks to Steve's comment, I am now using the following, which is pretty reliable.
ChartObject
that ChartObject
which is not activated at the time of export creates a file whose width and height are 1 more than it should be.
It remains to figure out how to automatically determine the factors px2ptH
and 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
source to share
Dimensions are in points, not pixels. 72 indicates an inch.
800px / 72 = 11.11111 .... The size of the exported image will be the size in inches / dpi of your computer display, usually 96 (as in your case, but you can't always count on it ... use WIN API calls to find the current values)
Randy Birch posted code that you can use to access WinAPI calls to get screen resolutions and more.
Go to http://vbnet.mvps.org/index.html and use the search function on the left to find GETDEVICECAPS
source to share