无法定义第6个范围对象

时间:2014-06-30 13:51:00

标签: excel excel-vba vba

我定义了不同的范围,以便我可以将它们用于图形:

Sub rangesGRAPHS()
Dim count, counter, Erow, Prow1, Prow2, Urow1 As Long
Dim Dsrc1, Dsrc2, Dsrc3, Xsrc1, Xsrc2, Xsrc3 As Range

counter = 5
count = Application.CountA(Range("A:A"))
count = count + 3

While counter < count
    If Range("Q" & CStr(counter)) = "ECO_BS" Then Erow = counter
    If Range("Q" & CStr(counter)) = "PHO_BS" Then Prow2 = counter
    counter = counter + 1
Wend

Prow1 = Erow + 1
Urow1 = Prow2 + 1

Dsrc1 = ("P5:P" & CStr(Erow))
Dsrc2 = ("P" & CStr(Prow1) & ":P" & CStr(Prow2))
Dsrc3 = ("P" & CStr(Urow1) & ":P" & CStr(count))
Xsrc1 = ("$C$5:$C$" & CStr(Erow))
Xsrc2 = ("$C$" & CStr(Prow1) & ":$C$" & CStr(Prow2))
Xsrc3 = ("$C$" & CStr(Urow1) & ":$C$" & CStr(count))

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc1)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc1)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc2)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc2)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc3)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc3)

除了行Xsrc3 = ("$C$" & CStr(Urow1) & ":$C$" & CStr(count))之外,其他所有内容都有效,error 91: object variable not set

调试时,我注意到Xsrc3设置为nothing。然而,所有其他的东西都有效,并且它是以相同的方式写的。如果我发表评论,其他的东西仍然有效。我不明白发生了什么 - 让我知道发生了什么!

1 个答案:

答案 0 :(得分:1)

它实际上并没有以同样的方式编写。在这一行:

Dim Dsrc1, Dsrc2, Dsrc3, Xsrc1, Xsrc2, Xsrc3 As Range

前5个变量实际上被声明为Variant,只有最后一个被声明为Range。你实际上希望它们都是String,所以使用:

Dim Dsrc1 As String, Dsrc2 As String, Dsrc3 As String, Xsrc1 As String, Xsrc2 As String, Xsrc3 As String