如何使用Excel VBA调整图表大小以适合页面大小?

我试图在Excel中调整一个图表的大小,使其完全符合可打印区域,例如图表应该覆盖整个A4页面, 除了边空白区域 ,即它应该覆盖(A4 height - top and bottom margins) x (A4 width - left and right margins) 。 我已经尝试了下面的代码,但事实certificate,图表的高度与(A4高度 – 上下边距)非常接近,但仍不完全相同,而宽度比(A4宽度 – 左右边距)。

 Private Sub Worksheet_Activate() Dim sh As Worksheet Dim objChartShape As Chart Set sh = ActiveSheet If sh.ChartObjects.Count <> 0 Then sh.ChartObjects.Delete End If Set objChartShape = sh.Shapes.AddChart.Chart Dim w, h As Long w = Application.CentimetersToPoints(21#) ' A4 width in cm h = Application.CentimetersToPoints(29.7) ' A4 height in cm w = w - sh.PageSetup.LeftMargin - sh.PageSetup.RightMargin h = h - sh.PageSetup.TopMargin - sh.PageSetup.BottomMargin With objChartShape .Parent.Left = 0 .Parent.Top = 0 .Parent.Width = w .Parent.Height = h End With End Sub 

上面的代码在表单被激活时创build一个空的图表。 您将看到图表不够高,无法达到页脚区域的顶部,并且太宽而无法放在一个页面中。

任何帮助将不胜感激,在此先感谢!

可能你也需要考虑页眉和页脚边距?

 Private Sub Worksheet_Activate() Dim sh As Worksheet Dim objChartShape As Chart Set sh = ActiveSheet If sh.ChartObjects.Count <> 0 Then sh.ChartObjects.Delete End If Set objChartShape = sh.Shapes.AddChart.Chart Dim w, h As Long w = Application.CentimetersToPoints(21#) ' A4 width in cm h = Application.CentimetersToPoints(29.7) ' A4 height in cm w = w - sh.PageSetup.LeftMargin - sh.PageSetup.RightMargin h = h - sh.PageSetup.TopMargin - sh.PageSetup.BottomMargin - sh.PageSetup.HeaderMargin - sh.PageSetup.FooterMargin With objChartShape .Parent.Left = 0 .Parent.Top = 0 .Parent.Width = w .Parent.Height = h End With End Sub