【问题标题】:How to adjust chart size to fit page size using Excel VBA?如何使用 Excel VBA 调整图表大小以适应页面大小?
【发布时间】:2014-05-23 08:55:19
【问题描述】:

我正在尝试调整 Excel 中图表的大小以完全适合可打印区域,例如图表应覆盖整个 A4 页面除边距区域,即应覆盖(A4 height - top and bottom margins) x (A4 width - left and right margins) 区域。我尝试了以下代码,但事实证明图表的高度非常接近但仍不完全相同(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

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

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

【问题讨论】:

  • 您知道可以将图表移动到其自己的工作表中,您可以在其中将大小设置为 A4 并在视图下设置边距?
  • 干杯,@Siphor。图表是否在自己的工作表中对我来说并不重要。问题是如何将其大小设置为 A4 减去所有边距。我上面的代码尝试这样做,但没有工作。
  • 老问题,但在这里。您正在使用嵌入在工作表中的图表对象。也许直接使用图表会更好,因为它会自动调整大小以适应页边距。

标签: vba excel charts


【解决方案1】:

您可能还需要考虑页眉和页脚边距?:

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

【讨论】:

  • 干杯,@Dave.Gugg,恐怕这行不通。我一开始尝试了完全相同的代码,我意识到页眉边距在上边距内,页脚边距在下边距内。此外,这也不会改变不适合页面大小的图表的宽度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
相关资源
最近更新 更多