美好的一天
我正在尝试遍历一个范围,而在该范围内我需要循环遍历另一个范围。
虽然这确实有用,但它会让你知道我想要实现的目标:
' 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
感谢您抽出宝贵时间。
罗布
答案 0 :(得分:0)
这是一个这个循环的快速实现,从一个看起来像这样的文件开始:
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