简体   繁体   中英

subscript out of range while adding items to array

I'm trying to fill an array with members from an AD group. I keep getting the following error while trying to set newArray(count) to the user name.

Microsoft VBScript runtime error: Subscript out of range

Here is the relevant code:

'set up of domain variables and stuff, verified working
Dim newArray()
Dim x
x = 0

Do While x < 1
    Set objGroup = GetObject("WinNT://" & strDomain & "/" & strGroup & ",group")
    count = 0
    For Each objUser In objGroup.Members
        newArray(count) = objUser.FullName
        count = count + 1
    Next
....

Your

Dim newArray()

creates an abomination: an array of no size that can't be grown, because UBound fails:

>> Dim aBomination()
>> ub = UBound(aBomination)
>>
Error Number:       9
Error Description:  Subscript out of range

The correct way to create a dynamic array with a size determined at run time (eg 17, it cound be -1 if you want to start with an array of no elments) and - if need be - grow it later is:

>> ReDim aGood(17)
>> ub = UBound(aGood)
>> WScript.Echo ub
>> ReDim aGood(UBound(aGood) + 1)
>> aGood(UBound(aGood)) = "tail"
>> WScript.Echo UBound(aGood), aGood(UBound(aGood))
>>
17
18 tail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM