2014-05-23 250 views
2

我試圖在Excel中調整圖表的大小以準確地適合可打印區域,例如圖表應該覆蓋整個A4頁面,除了邊緣區域,即它應該覆蓋(A4 height - top and bottom margins) x (A4 width - left and right margins)的區域。我已經嘗試了下面的代碼,但事實證明,圖表的高度與(A4高度 - 頂部和底部邊距)非常接近,但仍不完全相同,而寬度大約比(A4寬度 - 左右邊距)。如何使用Excel VBA調整圖表大小以適合頁面大小?

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

你知道你可以將圖表移動到其自己的工作表,您可以設置大小爲A4和下視的保證金? – Siphor

+0

乾杯,@Siphor。圖表是否在自己的表格中對我來說無關緊要。問題是如何將其大小設置爲A4減去所有邊距。我上面的代碼試圖這樣做,但沒有奏效。 – james

+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 
+0

乾杯,@ Dave.Gugg,恐怕這是行不通的。我已經嘗試了完全相同的代碼,並且我意識到頁眉邊距位於頂部邊距內,頁腳邊距位於底部邊距內。此外,這不會更改不適合頁面大小的圖表寬度。 – james