Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SomeArray.Append ???? 1

Status
Not open for further replies.

IknowMe

Programmer
Aug 6, 2004
1,214
US
Using the Language Real Basic I was able to add elements to an array like this
Code:
'Real Basic Code

    Dim Test() As String

    'Here's how I'm used to doing it
    Test.Append "Blah Blah 0"
    Test.Append "Blah Blah 1"
    Test.Append "Blah Blah 2"

I haven't had any luck finding similar functionality in VBA, so I tried writing a Sub.

Code:
Sub Main()

Dim Test() As String

    For x = 0 To 2
        'Attempt at workaround
        Call StuffArray(Test, "Blah Blah" & Str(x))
        MsgBox Test(x)
    Next
    
End Sub


Sub StuffArray(ByRef StuffThisArray As Variant, sStuffThis As String)
    
    ReDim Preserve StuffThisArray(UBound(StuffThisArray) + 1)
    StuffThisArray(UBound(StuffThisArray)) = sStuffThis
    
End Sub

I can't get the Sub to work, I believe because UBound(StuffThisArray) is Nil the first go around.

I know it could be done like this Test = Array("Blah Blah 0", "Blah Blah 1", "Blah Blah 2"), but I don't know all of the strings I'll be adding at once and was hoping to avoid sArrayElements = sArrayElements & "," & sNewElement. Any suggestions?



[thumbsup2] Wow, I'm having amnesia and deja vu at the same time.
I think I've forgotten this before.


 
Hi there,

Take a look at the ReDim and Preserve commands. Post back if you need more help.

Regards,
Zack Barresse

Simplicity is the ultimate sophistication. What is a MS MVP? PODA
- Leonardo da Vinci
 
Hi MrMilson,

AFAIK there is no 'proper' way to determine whether an array has been initialised or not and you must either keep a flag or trap an error, something like this ...
Code:
[blue]Sub StuffArray(ByRef StuffThisArray As Variant, sStuffThis As String)
    
    Dim TempUB As Long
    TempUB = -1
    On Error Resume Next
        TempUB = UBound(StuffThisArray)
    On Error GoTo 0
    
    ReDim Preserve StuffThisArray(TempUB + 1)
    StuffThisArray(UBound(StuffThisArray)) = sStuffThis
    
End Sub[/blue]

Enjoy,
Tony

--------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.

Professional Office Developers Association
 
@Tony

Thanks that works great!

[thumbsup2] Wow, I'm having amnesia and deja vu at the same time.
I think I've forgotten this before.


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top