简体   繁体   English

循环VBA Excel末尾为空数组

[英]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: 我试图清除数组中累积的值,并在columns循环的末尾将其清空:

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. 从上面的代码中可以看到,我得到了一个msgbox,它在每个循环的末尾显示值,但是随着它的继续,数组不断增大,表明Erase行不起作用。

Kindly help! 请帮助!

You can either use a loop to set the array elements to nulls, or ReDim the array away: 既可以使用一个循环到阵列元件设置为空值,或REDIM阵列远:

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. 这样,您可以稍后在子目录中重复使用相同的阵列名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM