VBScript Basics, Part 45 | Adding to an Array (Arrays)

VBScripting (.vbs) Basic tutorial on how to add to an existing array, using the ReDim and Preserve, and UBound commands.

Code Example:

Option Explicit
Dim Files, File, myArray
Dim objFSO : Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Set Files = objFSO.GetFolder(CreateObject(“Wscript.Shell”).SpecialFolders(“Desktop”)).Files
myArray = Array()
For Each File In Files
ReDim Preserve myArray(UBound(myArray) + 1)
myArray(UBound(myArray)) = File.Name

MsgBox Join(myArray, vbLf)


Option Explicit
Dim Animals, objSHL

Animals = Array(“Horse”, “Turtle”, “Rabbit”, “Squirrel”, “Pig”)

Animals = AddtoArray(Animals)

With CreateObject(“Wscript.Shell”)
.run “notepad.exe”
WScript.Sleep 1000
.sendkeys Join(Animals, vbLf)
End With

Function AddtoArray(CurrArray)
Dim Value
If IsArray(CurrArray) Then
Value = InputBox(Join(CurrArray,vbLf),”Add to your array.”)
ReDim Preserve CurrArray(UBound(CurrArray) + 1)
CurrArray(UBound(CurrArray)) = Value
Loop Until Value = “”
End If
AddtoArray = CurrArray
End Function