7

So i have a vb script that sweeps through RAP (Run advertised programs) and if the program has no last run time, but that program's full name into an array, then i have this array echo to a message box. I intialize the array to store 10 values, however to keep the message box clean i wanted to ReDim the array size once it had found all the programs (shoudn't ever be more than 3 but who knows with clients). However i can't seem to get the array to resize and it prints a message box with 10 array slots + the program it found.

Dim vprglist(10)
Dim i  
Dim strBuf 
Dim intIndex 

Set vprograms = oUIResource.GetAvailableApplications

i = 0 
For Each vprogram In vprograms
     If vprogram.LastRunTime = "" Then
         vprglist(i) = vprogram.FullName
         i = i + 1
     End If   
Next

ReDim Preserve vprglist(i)

If vprglist <> Null Then  

    For intIndex = LBound(vprglist) To UBound(vprglist)
        strBuf = strBuf & "   -  " & vprglist(intIndex) & vbLf 
    Next
        vmsgbox = MsgBox("Do you want to Install(Yes) or Defer(No) the follow software: " & vbLf & strBuf,64+4)
        Select Case vmsgbox
user2146211
  • 109
  • 1
  • 2
  • 6

1 Answers1

14

You can't re-dimension a fixed-size array (Dim vprglist(10)). If you want a dynamic array, define a "normal" variable and assign an empty array to it:

Dim vprglist : vprglist = Array()

or define it directly with ReDim:

ReDim vprglist(-1)

Then you can re-dimension the array like this:

If vprogram.LastRunTime = "" Then
  ReDim Preserve vprglist(UBound(vprglist)+1)
  vprglist(UBound(vprglist)) = vprogram.FullName
  i = i + 1
End If

ReDim Preserve will copy all elements of the array into a new array, though, so it won't perform too well in the large scale. If performance is an issue, you'd better use the System.Collections.ArrayList class instead:

Dim vprglist : Set vprglist = CreateObject("System.Collections.ArrayList")
...
If vprogram.LastRunTime = "" Then
  vprglist.Add vprogram.FullName
  i = i + 1
End If
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • no the list shouldn't get any bigger than 10, and that would be rare, thank you for this. – user2146211 Jul 15 '13 at 21:53
  • 1
    Using `System.Collections.ArrayList` straight-away was the best solution for me – bobobobo Nov 27 '21 at 02:40
  • With `System.Collections.ArrayList ` (on Win10): "_An app on your PC needs the following Windows feature: .NET Framework 3.5 (includes .NET 2.0 and 3.0)_". You have to be Admin to "_Download and install this feature_". – Gerold Broser Feb 27 '23 at 01:26