1

I'm trying to run a VBA application using a loop and using variables whose names depends on where in the loop I am. Specifically something like

Dim i As Integer
i = 1
Dim varname() As String
while i < 50
varname(i) = asdasd
i = i + 1
Wend

Somehow it can't read varname(i) or whatever. It reports subscript out of range.
I have no idea what the problem is, can someone helt me perhaps?

1 Answer 1

2

You need to give your array a capacity first.

Sub max()

Dim i As Integer
i = 1

Dim varname() As String
ReDim varname(49) '<---- There

While i < 50
varname(i) = asdasd
i = i + 1
Wend


End Sub

This is a good resource for VBA arrays: http://msdn.microsoft.com/en-us/library/office/aa164778(v=office.10).aspx

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

3 Comments

Ah okay. Can I update the ReDim later on, without destroying existing variables? Since the dimension in my actual code will depend on some if outcomes.. So at the start I don't know the final number of variables I'll need.
yes, the command to use there instead would be ReDim Preserve
I think you can just use Dim varname(49) as String without needing ReDim.

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.