1

I create a chart in Excel using this VBA.

myRange = "Sheet1!$A$1,Sheet1!$A$3,Sheet1!$A$8,Sheet1!$A$13,Sheet1!$A$18,Sheet1!$A$23,Sheet1!$A$28,Sheet1!$A$34,Sheet1!$A$41,Sheet1!$A$48,Sheet1!$D$1,Sheet1!$D$3,Sheet1!$D$8,Sheet1!$D$13,Sheet1!$D$18,Sheet1!$D$23,Sheet1!$D$28,Sheet1!$D$34,Sheet1!$D$41,Sheet1!$D$48"
    
ActiveSheet.Shapes.AddChart2(227, xlLine).Select
ActiveChart.SetSourceData Source:=Range( _
    myRange _
    )

When I add another couple of cells into the myRange variable (...,Sheet1!$A$55... ,Sheet1!$D$55), like this:

myRange = "Sheet1!$A$1,Sheet1!$A$3,Sheet1!$A$8,Sheet1!$A$13,Sheet1!$A$18,Sheet1!$A$23,Sheet1!$A$28,Sheet1!$A$34,Sheet1!$A$41,Sheet1!$A$48,Sheet1!$A$55,Sheet1!$D$1,Sheet1!$D$3,Sheet1!$D$8,Sheet1!$D$13,Sheet1!$D$18,Sheet1!$D$23,Sheet1!$D$28,Sheet1!$D$34,Sheet1!$D$41,Sheet1!$D$48,Sheet1!$D$55"

I get this error:

Run-time error '1004'
Method 'Range' of object '_Global' failed

2 Answers 2

4

It's the limit of 255 characters. Use

myRange = "$A$1,$A$3,..."
    
ActiveSheet.Shapes.AddChart2(227, xlLine).Select
ActiveChart.SetSourceData Source:=Sheet1.Range( _
    myRange _
    )

instead, where Sheet1 is the code name of "Sheet1".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It is working now. How about if the sheet grows until I reach the 255 characters limit, even taking off 'Sheet1', from it?
In this case you need to optimize the references as per @CDP1802 answer, or use Union method, or put values (or their copies) into the continuous range like "X1:X10".
2
Dim rng as range
Set rng = Sheet1.Range("A1,A3,A8,A13,A18,A23,A28,A34,A41,A48,A55")
ActiveSheet.Shapes.AddChart2(227, xlLine).Select
ActiveChart.SetSourceData Source:=Union(rng, rng.Offset(, 3))

1 Comment

Yes, the absolute address notation has no sense in this context. "Union"+"Offset" also adds more clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.