簡體   English   中英

帶VBA的Excel中圖表數據源的變量

[英]Variable of source of data for chart In Excel With VBA

我正在使用Excel 2007 VBA在同一數據表中創建ScatterSmoothNoMarkers類型圖表。 我的源數據取決於打開的許多文本文件。 X值在位置A2:A200處是固定的。 並且Series值列的ID將更改。

如果我打開2個文件,我的源數據將是: Range(A2:A200, F2:G200) 要打開3個文件,我的源數據將是: Range(A2:A200, H2:J200)等等……所以我需要用變量替換那些列ID。 但是在設置數據源時出現錯誤。 這是我的代碼:

Sub addChart()
Dim n as integer ‘files count and also the number of columns for chart1 
Dim intColStart, intColStop as integer  ‘number of columns for chart 1
intColStart = n*2+2  ‘this is a formula to find the ID of the start column of chart1
intColStop = n*3+1  ‘this is a formula to find the ID of the stop column of chart1
…..
With ActiveSheet.ChartObjects.Add _
         (Left:=100, Width:=375, Top:=75, Height:=225)
        .Chart.SetSourceData Source:=Sheets("Sheet1").Range("A2:A200, intColStart:intColStop ")  ‘’’’’PROBLEM RIGHT HERE‘’’’’’’
        .Chart.ChartType = xlXYScatterSmoothNoMarkers
……..
End With
End Sub 

任何幫助都感激不盡。

您不能在"標記內引用變量。VBA不知道如何轉換它們,因此它認為您正在設置一個Range其中包括您實際上試圖使用的文本

A2:A200, intColStart:intColStop 

這對VBA沒有任何意義。

為什么不換線

    .Chart.SetSourceData Source:=Sheets("Sheet1").Range("A2:A200, intColStart:intColStop ") 

    .Chart.SetSourceData Source:=Sheets("Sheet1").Range(Cells(2,2), Cells(200,intColStop))

如果我誤解了您的興趣,我將建議您在手動創建Range String輸入的地方使用以下內容:

dim rngStr as String
dim firstColStr as String
dim secondColStr as String
firstColStr = ColumnLetter(intColStart)
secondColStr = ColumnLetter(intColStop)
rngStr = "A2:A200," & firstColStr & ":2:" & secondColStr & "200"
...

.Chart.SetSourceData Source:=Sheets("Sheet1").Range(rngStr)

這個答案定義了我在ColumnLetter函數(它從索引中獲取字母)。

暫無
暫無

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

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