Как петлю через диапазон, пока уже зацикливается через другой диапазон

StackOverflow https://stackoverflow.com//questions/23057245

Вопрос

Хороший день

Я пытаюсь закрутить диапазон и в то время как в этом диапазоне мне нужно петлю через другой.

Хотя это делает работу, это даст вам представление о том, что я пытаюсь достичь:

    ' Select cell M5, *first line of data*.
    Range("M5").Select
    ' Set Do loop to stop when an empty cell is reached.
    Do Until IsEmpty(ActiveCell)
        strReg = ActiveCell.Value
        dteDate = ActiveCell.Offset(0, 1).Value
        lngRate = ActiveCell.Offset(0, 2).Value
        Range("G5").Select
        Do Until blnFound Or IsEmpty(ActiveCell)
            If ActiveCell.Value = strReg Then
                If ActiveCell.Offset(0, -3) <= dteDate And ActiveCell.Offset(0, -2) >= dteDate Then
                     blnFound = True
                     '... add more logic here
                End If
            End If
            ' Step down 1 row from present location.
            ActiveCell.Offset(1, 0).Select
        Loop
        ' Step down 1 row from present location.
        ActiveCell.Offset(1, 0).Select
    Loop
.

Спасибо, что нашли время.

Роб

Это было полезно?

Решение

Вот быстрая реализация этой петли, запущенная с файлом, который выглядит так:

Start

Option Explicit
Sub LoopThroughVehicles()

Dim MySheet As Worksheet
Dim CostRange As Range, InvoiceRange As Range, _
    FoundRange As Range, Vehicle As Range
Dim LastRow As Long, CostVehicleCol As Long, _
    InvoiceVehicleCol As Long
Dim CostDate As Date, StartDate As Date, _
    EndDate As Date

'assign variables and ranges for easy reference
CostVehicleCol = 13 'column M
InvoiceVehicleCol = 7 'column G
Set MySheet = ThisWorkbook.Worksheets("Sheet1")
With MySheet
    LastRow = .Range("M" & .Rows.Count).End(xlUp).Row
End With
Set CostRange = Range(MySheet.Cells(LastRow, CostVehicleCol), MySheet.Cells(5, CostVehicleCol))
With MySheet
    LastRow = .Range("G" & .Rows.Count).End(xlUp).Row
End With
Set InvoiceRange = Range(MySheet.Cells(LastRow, InvoiceVehicleCol), MySheet.Cells(5, InvoiceVehicleCol))

'search for each vehicle
For Each Vehicle In CostRange
    Set FoundRange = InvoiceRange.Find(What:=Vehicle.Value, LookAt:=xlWhole, MatchCase:=False)
    'if the vehicle is found, assign dates and compare
    If Not FoundRange Is Nothing Then
        CostDate = Vehicle.Offset(0, 1).Value
        StartDate = FoundRange.Offset(0, -3).Value
        EndDate = FoundRange.Offset(0, -2).Value
        If CostDate >= StartDate And CostDate <= EndDate Then
            'do stuff if cost date is in date range
            MsgBox ("Cool, " & Vehicle.Value & " is in the date range!")
        Else
            'do other stuff if cost date is not in date range
            MsgBox ("Uh oh, " & Vehicle.Value & " is NOT in the date range!")
        End If
    End If
Next Vehicle

End Sub
.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top