簡體   English   中英

Excel VBA將數據添加到圖表

[英]Excel VBA adding data to a chart

您好,我有一個將數據添加到現有圖表中的問題。

現在,我在工作表的第二行中有了一個工作表,其中包含一個年份為月份的數據系列。 因此,例如,月份是B2 1.2017,C2 2.2017,並且在第3、4、5、6、7和8行中始終有該月份的數據。

現在,我只希望宏將新的Month以及下面各行的數據添加到現有圖表中。

我到目前為止的代碼是這樣的:

Worksheets("Summary").ChartObjects("Chart").Activate
   ActiveChart.SeriesCollection.Add _
   Source:=Worksheets("Summary").Range("B2:B8")

現在這只是創建新的數據系列,但實際上沒有向圖表添加任何新數據。

下面的代碼可能看起來有些長,但這是向現有圖表添加帶有數據的新Series的最安全方法。

我設置了所有必需的Objects因此代碼將盡可能地“安全”。

Option Explicit

Sub AddSeriestoChart()

Dim ws As Worksheet
Dim ChtRng As Range
Dim ChtObj As ChartObject
Dim Ser As Series

' set the Worksheet object
Set ws = ThisWorkbook.Worksheets("Summary")

' Set the Chart Object
Set ChtObj = ws.ChartObjects("Chart")

' Set the Range of the Chart's source data
Set ChtRng = ws.Range("B2:B8")

With ChtObj
    ' add a new series to chart
    Set Ser = .Chart.SeriesCollection.NewSeries

    ' set the source data of the new series
    Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)
End With

End Sub

編輯1 :要修改現有的Series數據,請使用以下代碼:

With ChtObj          
    For i = 1 To .Chart.SeriesCollection.Count
        Set Ser = .Chart.SeriesCollection(i)

        ' set the source data of the new series
        Set ChtRng = ws.Range("B" & i + 2)
        Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)

        Set ChtRng = Nothing
    Next i
End With

這就是我會用的

wsMetric.ChartObjects("Chart").Chart

'This one will link data from another workbook
.SeriesCollection(1).Values = "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow  & ":$" & sCol2 & "$" & lRow2 
'Debug.Print "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow  & ":$" & sCol2 & "$" & lRow2 'Returns ='[Book1.xlsm]Sheet1'!$A$1:$A$11


'This one will link data from the same workbook, same or different sheet
.SeriesCollection(1).Values = "=" & ws.Name & "!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow 2
'Debug.print "=" & ActiveSheet.Name & "!$" & scol & "$" & lrow & ":$" & scol2 & "$" & lrow2 'Returns =Sheet1!$A$1:$A$11
End With

這不使用.Activate並直接訪問圖表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM