0

I'm just trying to initialize an array in VBScript without specify its size and I'm getting the error: "Subscript out of range".

Option Explicit 
dim arr()
arr(0)=2
Call MsgBox("arr: " & arr(0)) 'It prints 2

When I just edit the 2nd line to dim arr(1) it works.

I wonder it is a bug. Or I'm missing something?

I'm newbie with VBScript

3
  • What are you trying to accomplish by initializing an array without defining its size? As you've seen -- it isn't possible. What are you hoping to do? Perhaps there is a better way. Commented May 5, 2016 at 11:56
  • @JohnColeman, That's because I dont know how many elements will be inserted in this array. Sometimes it can be hundreds or thousands Commented May 5, 2016 at 12:04
  • In case you don't know the size upfront, use ReDim Preserve to size the array without losing the contents Commented May 5, 2016 at 12:07

2 Answers 2

2

@PankajJaju already gave a good answer to your basic question.

If your intention is to have an array which can dynamically expand as needed, you might want to use an array list:

Option Explicit
dim arr

Set arr = CreateObject("System.Collections.ArrayList")
arr.add 2

msgbox "arr: " & arr(0) 'it *does* print 2!

In addition to being able to expand dynamically, array lists also have a nice sort method. The link I gave above shows how to use them from VBScript.

(Also -- note that you can invoke subs without the keyword Call -- though if you do so with a sub as opposed to a function you need to drop parentheses around the arguments the way I did with msgbox).

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

Comments

2

When you do dim arr() it means its without any size. So to use it, you first need to make sure that you specify a size while declaring like dim arr(1) or by using ReDim arry(1).

Basics

http://www.w3schools.com/asp/vbscript_variables.asp

https://msdn.microsoft.com/en-us/library/t7zd6etz(v=vs.84).aspx

Comments

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.