从UBound到LBound的循环数组并检查值

时间:2019-01-24 14:57:46

标签: excel vba

我正在尝试创建一个数组,从UBoundLBound循环并使用以下代码检查值。

我在网上收到错误消息:

 If arrPart(i) = strResult Then
  

运行时错误9

我尝试在数组中导入的范围:

enter image description here

代码:

    Option Explicit

    Sub ArrayTest()

        Dim LastColumn As Long, CounterPart As Long, i As Long
        Dim arrPart As Variant
        Dim strResult As String

        With ThisWorkbook.Worksheets("Sheet1")

            LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

            strResult = "N"

            'Set as an array the 4 last matches
            arrPart = .Range(Cells(1, LastColumn - 3), Cells(1, LastColumn))

            CounterPart = 0

            For i = UBound(arrPart) To LBound(arrPart) Step -1

                If arrPart(i) = strResult Then
                    CounterPart = CounterPart + 1
                Else
                    Exit For
                End If

            Next

        End With

    End Sub

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

根据以上所有评论:

Option Explicit

Sub ArrayTest()

    Dim LastColumn As Long, CounterPart As Long, i As Long
    Dim arrPart As Variant
    Dim strResult As String

    With ThisWorkbook.Worksheets("Sheet1")

        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

        strResult = "N"

        'Set as an array the 4 last matches
        arrPart = .Range(.Cells(1, 1), .Cells(1, LastColumn))

        CounterPart = 0

        For i = UBound(arrPart, 2) To LBound(arrPart, 2) Step -1

            If arrPart(1, i) = strResult Then
                CounterPart = CounterPart + 1
            Else
                Exit For
            End If

        Next

    End With

    Debug.Print CounterPart
End Sub

答案 1 :(得分:0)

假设您有一个从B4开始的单元格表。

scren

这是您找出表的大小,将值传输到数组中并对其进行迭代的方式。

Public Sub ArrayTest()

    Dim r_start As Range
    Set r_start = Range("B4")

    Dim i As Long, n As Long
    n = Range(r_start, r_start.End(xlToRight)).Columns.Count

    Dim arrPart() As Variant
    arrPart = r_start.Resize(1, n).Value

    Dim strResult As String
    strResult = "N"

    Dim counter As Long
    counter = 0

    For i = 1 To n
        If arrPart(1, i) = strResult Then
            counter = counter + 1
        Else
            Exit For
        End If
    Next i

    Debug.Print counter

End Sub