Skip to content

Instantly share code, notes, and snippets.

@sholsinger
Created April 4, 2011 16:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sholsinger/901874 to your computer and use it in GitHub Desktop.
VBScript Tools for measuring the length of an array and appending values to a Dynamic array
' appends the second argument to the first if the first is an array.
' MUST be a dynamic array! Returns new array.
' Usage:
' Dim myArray()
' myArray = ArrayAppend(myArray, "foo")
Function ArrayAppend( a, o )
On Error Resume Next
Err.Clear()
dim tn, i
i = 0
tn = TypeName(o)
If isArray(a) Then
i = UBound(a)
If Err.number <> 0 Then
Err.Clear() ' We know this causes an error every time.
Else
i = i+1
End If
ReDim Preserve a(i)
If tn <> "Object" Then
a(i) = o
Else
Set a(i) = o
End If
End If
ArrayAppend = a
End Function
' gets the length of an array.
Function ArrayLength( a )
On Error Resume Next
dim i: i = 0
i = UBound(a) + 1
ArrayLength = i
Err.Clear()
End Function
@keenskelly
Copy link

Thanks for these. I refactored them to fit a little better with our development style; mostly code reduction, plus an early exit if a is supplied as a non-array for the append function:

' appends the second argument to the first if the first is an array.
' MUST be a dynamic array! Returns new array.
' like so : myArray = ArrayAppend(myArray, "foo")
FUNCTION ArrayAppend(a, o )
    ON ERROR RESUME NEXT
    Err.Clear()
    IF (NOT isArray(a)) THEN
        ArrayAppend = a
        EXIT FUNCTION
    END IF
    DIM tn, i
    i = UBound(a)
    ' We know this causes an error every time.
    IF (Err.number <> 0) THEN Err.Clear() ELSE i = i + 1
    REDIM PRESERVE a(i)
    tn = TYPENAME(o)
    IF (tn <> "Object") THEN a(i) = o ELSE SET a(i) = o
    ArrayAppend = a
END FUNCTION

' gets the length of an array.
FUNCTION ArrayLength( a )
    ON ERROR RESUME NEXT
    DIM i
    i = UBound(a) + 1
    ArrayLength = i
    Err.Clear()
END FUNCTION

@sholsinger
Copy link
Author

I'm glad they were helpful to someone else as well. Thanks for the feedback.

@keenskelly
Copy link

keenskelly commented Jun 3, 2011 via email

@sholsinger
Copy link
Author

You may also find this one useful: https://gist.github.com/943116

inArray(array, object) ' = index or -1 if not found.

@sholsinger
Copy link
Author

Keenskelly I think I might have figured out what your problem was. I tried to use the ArrayAppend() method to append an array to another array and that doesn't work. It will work on all primitives though -- and might work for Objects. The logic to re-dim an array into a multi-dimensional array is just much more than I'm willing to spend time writing right now. I hate the way VBScript handles arrays.

@keenskelly
Copy link

keenskelly commented Jul 7, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment