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?")

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

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?
a collection 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.
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.
I did not know about Collections object, Mehow. It seems more interesting than Arrays.. I'll try reading something about them now. Thanks again
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.