2017-08-23 86 views
0

我試圖從表格中生成圖表。生成圖表時出現自動化錯誤

該表位於我的工作表「測試」中,我希望我的工作表位於工作表「狀態」中。

我使用的代碼中,我在該行

.SetSourceData Source:=rng 

我沒有得到錯誤每次收到一個自動化錯誤。對於每30次或更多的迭代,我得到這個錯誤。

誰能幫助下,我怎麼能糾正這種

Sub chart() 
Dim rng As Range 
Dim cht As Object 
Dim Ws As Worksheet 
Set Ws = Sheets("Test") 
Set rng = Ws.Range("G1:J2") 
Set sh = ActiveSheet.ChartObjects.Add(Left:=400, _ 
    Width:=390, _ 
    Top:=100, _ 
    Height:=250) 
sh.Select 
Set cht = ActiveChart 
With cht 
.SetSourceData Source:=rng 
.ChartType = xlColumnClustered 
ActiveChart.FullSeriesCollection(1).Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
ActiveChart.FullSeriesCollection(1).Points(2).Format.Fill.ForeColor.RGB = RGB(0, 255, 0) 
    ActiveChart.FullSeriesCollection(1).Points(3).Format.Fill.ForeColor.RGB = RGB(0, 0, 255) 
    ActiveChart.FullSeriesCollection(1).Points(4).Format.Fill.ForeColor.RGB = RGB(80, 100, 10) 
'cht.Axes(xlSecondary).TickLabels.NumberFormat = "0.0%" 
End With 
'cht.SeriesCollection(1).name = "" 
cht.SeriesCollection(1).HasDataLabels = True 
cht.HasTitle = True 
cht.ChartTitle.Text = "Status" 
End Sub 

回答

2

試試這個:

Sub chart() 
    Dim rng As Range 
    Dim cht As Chart 
    Dim Ws As Worksheet 

    Set Ws = ThisWorkbook.Sheets("Test") 
    Set rng = Ws.Range("G1:J2") 
    Set sh = ThisWorkbook.Sheets("status") 

    sh.Shapes.AddChart(Left:=400, Top:=100, Width:=390, Height:=250).Select 
    Set cht = ActiveChart 

    With cht 
     .SetSourceData Source:=rng 
     .ChartType = xlColumnClustered 
     .SeriesCollection(1).Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
     .SeriesCollection(1).Points(2).Format.Fill.ForeColor.RGB = RGB(0, 255, 0) 
     .SeriesCollection(1).Points(3).Format.Fill.ForeColor.RGB = RGB(0, 0, 255) 
     .SeriesCollection(1).Points(4).Format.Fill.ForeColor.RGB = RGB(80, 100, 10) 
     .ChartTitle.Text = "Status" 
    End With 
End Sub