1

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?")
Community
  • 1
  • 1
AndroidDev
  • 831
  • 5
  • 17
  • 36

2 Answers2

0

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
  • Mehow, lets say that currently, the array has only 4 itens of 100. The statement will add the new array item to the 100 position. How can I add it to the next available position, that is, the 5th position? – AndroidDev Dec 02 '13 at 14:50
  • a [**collection**](http://stackoverflow.com/questions/10579457/why-use-arrays-in-vba-when-there-are-collections) would be more suitable in that case. You wouldn't have to specify the size of your collection at start and a simple method like `collectionObj.Add()` adds new items to the end of the current queue. –  Dec 02 '13 at 14:51
  • If you really wanted to use an array and add item to the next empty(unassigned) element in array this would be a good new question. –  Dec 02 '13 at 14:53
  • 1
    I did not know about Collections object, Mehow. It seems more interesting than Arrays.. I'll try reading something about them now. Thanks again – AndroidDev Dec 02 '13 at 14:56
0

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.

Steve Rindsberg
  • 14,442
  • 1
  • 29
  • 34