CaptainABC
CaptainABC

Reputation: 1239

Empty array at the end of the loop VBA Excel

I have the below code that adds values to an array if it meets a criteria.

It keeps looping horizontally through the columns across a row and then repeats the same for the next row and so on.

I am trying to clear the values accumulated in the array and empty it at the end of the columns loop:

For a = 21 To 23

    Count = 0
    For b = 2 To 36
    If Not Worksheets("Sheet1").Cells(a, b).Value = "A" And Not Worksheets("Sheet1").Cells(a, b).Value = "B" Then
    Count = Count + 1
    Else
    If Not Count = 0 Then

    Dim arr() As Long

    arrLen = 1
    ReDim Preserve arr(1 To arrLen)
    arr(arrLen) = Count
    arrLen = arrLen + 1

    For i = LBound(arr) To UBound(arr)
        msg = msg & arr(i) & vbNewLine
    Next i

    Count = 0
    End If
    End If
    Next b

    MsgBox Worksheets("Sheet1").Cells(a, 1).Value & vbNewLine & msg
    Erase arr 'not working

Next a

As you can see from the above code, I get a msgbox displaying the values at the end of each loop, however as it continues, the array keeps getting bigger and bigger indicating that the Erase line is not working.

Kindly help!

Upvotes: 0

Views: 4439

Answers (1)

Gary's Student
Gary's Student

Reputation: 96773

You can either use a loop to set the array elements to nulls, or ReDim the array away:

Sub marine()
    Dim arr()
    ReDim arr(1 To 2)
    arr(1) = "Alpha"
    arr(2) = "Beta"

    ReDim arr(1 To 1)
    arr(1) = ""
End Sub

That way you can re-use the same array name later in the sub.

Upvotes: 2

Related Questions