使用变量而不是列名或数字

时间:2011-03-04 08:49:57

标签: excel vba variables excel-vba

我正在尝试在Excel中绘制图表,这是我的代码

ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'ResultHL'!$E:$E")
ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Values = "='ResultHL'!$CB$1:$CB$2520"

这工作正常,但我不知道我是否可以为某些变量指定列名或数字,并在上面的代码中使用它。

第2行 - > ActiveChart.SetSourceData Source:=Range("'ResultHL'!$E:$E") 我需要将E分配给变量并使用它

同样在第5行,我需要使用整数变量而不是2520

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我发现使用Cells和/或Resize属性比在所有这些混乱的字符串连接业务中陷入困境要容易得多。

示例:

Dim rngApples As Range
Dim shtResults As Worksheet
Dim lngMaxRow As Long

shtResults = Worksheets("Sheet1")

' Define the range you want to plot
lngMaxRow = 2520
rngApples = shtResults.Range("CB1").Resize(lngMaxRow, 1)

ActiveChart.SeriesCollection(2).Values = rngApples 

或者,您可以按如下方式定义范围:

lngColNum = 56 ' or whatever CB is
lngMaxRow = 2520
rngApples = shtResults.Range(Cells(1, lngColNum), Cells(lngMaxRow, lngColNum))

答案 1 :(得分:1)

细胞与细胞范围说明符只是字符串,因此您可以使用字符串或数字对它们进行连接,以引用所需的单元格。

For example:
ActiveChart.SetSourceData Source:=Range("'ResultHL'!$E:$E")
Could become
ActiveChart.SetSourceData Source:=Range("'ResultHL'!$" & ColumnName & ":$" & ColumnName)
Where ColumnName is the string value of the column you wish to use. 

ActiveChart.SeriesCollection(2).Values = "='ResultHL'!$CB$1:$CB$2520"
Could become
ActiveChart.SeriesCollection(2).Values = "='ResultHL'!$CB$1:$CB$" & MaxRowNumber
相关问题