Цикл Array от UBound до LBound и проверка значений - PullRequest
0 голосов
/ 24 января 2019

Я пытаюсь создать массив, цикл от UBound до LBound и проверить значения с помощью приведенного ниже кода.

Я получаю сообщение об ошибке:

 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 голосов
/ 24 января 2019

Предположим, у вас есть таблица ячеек, начиная с 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
0 голосов
/ 24 января 2019

За все комментарии выше:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...