我正在尝试调整Excel中图表的大小以完全适合可打印区域,例如图表应覆盖整个A4页面 ,边距区域 ,即它应覆盖(A4 height - top and bottom margins) x (A4 width - left and right margins)
区域。我已经尝试了下面的代码,但事实证明图表的高度非常接近但仍然不完全相同(A4高度 - 顶部和底部边距),而宽度比宽度大约1个单元(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
上面的代码在激活工作表时创建一个空图表。您将看到图表不够高,无法到达页脚区域的顶部,并且它太宽而无法放入单个页面中。
非常感谢任何帮助,提前谢谢!
答案 0 :(得分:0)
您可能还需要考虑页眉和页脚边距?:
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