HDCerberus
HDCerberus

Reputation: 2143

Print an Array in VBA Subscript out of range

I have a set of strings in a column that I'm entering for later processing. I'd like to be able to print the array to view the array and understand changes that need made. In the sample below, there are values in all 14 cells. However, when I run this code I get a VBA "Run-time error '9': Subscript out of range' error.

 Sub Clean()
        Dim siteArrayOriginal()
        siteArrayOriginal() = Worksheets("Sheet1").Range("A1:A14").Value
        viewArray (siteArrayOriginal)
    End Sub

Public Function viewArray(myArray)
    Dim txt As String
    Dim i As Long

    For i = LBound(myArray) To UBound(myArray)
    txt = txt & myArray(i) & vbCrLf
    Next i

    MsgBox txt
End Function

Why?

Upvotes: 1

Views: 710

Answers (1)

Scott Craner
Scott Craner

Reputation: 152505

The array, though you are passing on one column, is still a two dimensional array.

So when referring to it you need to include the second dimension:

myArray(i, 1)

So:

Sub Clean()
    Dim siteArrayOriginal()
    siteArrayOriginal() = Worksheets("Sheet1").Range("A1:A14").Value
    viewArray (siteArrayOriginal)
End Sub

Public Function viewArray(myArray)
    Dim txt As String
    Dim i As Long

    For i = LBound(myArray) To UBound(myArray)
    txt = txt & myArray(i, 1) & vbCrLf
    Next i

    MsgBox txt
End Function

enter image description here

Upvotes: 2

Related Questions