I need to know how can I add an item to an existing array using a user input.
I tried something like this:
Dim MyArray(100) as String
UBound(MyArray) = Inputbox("What's the name of your new array item?")
I need to know how can I add an item to an existing array using a user input.
I tried something like this:
Dim MyArray(100) as String
UBound(MyArray) = Inputbox("What's the name of your new array item?")
Ubound(myArray)
returns a Long
datatype, it literally return the length/size of the array.
If you want to read or assign a value then you must fully qualify the array ie.
MyArray(ubound(myArray)) = "new Value"
or MyArray(100) = "new Value"
Sub Main()
Dim MyArray(100) As String
MyArray(UBound(MyArray)) = InputBox("What's the name of your new array item?")
MsgBox MyArray(UBound(MyArray))
End Sub
You could use a dynamic array instead:
Dim MyArray() As String
' Then to add a new element:
Redim Preserve MyArray(1 to SafeUBound(MyArray) + 1)
MyArray(SafeUBound(MyArray)) = InputBox("Who's yer daddy?")
Function SafeUBound(vArray As Variant) As Long
Dim x As Long
On Error Resume Next
x = UBound(vArray)
If Err.Number = 0 Then
SafeUBound = x
Else
SafeUBound = 0
End If
End Function
The call to SafeUbound is necessary because calling UBound or LBound on an uninitialized array will throw an error.