Comment boucle à travers une plage tout en boucle déjà à travers une autre gamme
-
23-12-2019 - |
Question
bonne journée
J'essaie de boucler à travers une gamme et que dans cette plage, j'ai besoin de boucler à travers une autre.
Bien que cela fonctionne, cela vous donnera une idée de ce que j'essaie d'atteindre:
' 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
Merci d'avoir pris le temps.
rob
La solution
Voici une implémentation rapide de cette boucle à partir d'un fichier qui ressemble à ceci:
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow