问题
I have data that starts in B3 and is dynamic so its range may be 5 rows to 500. I want to loop through the number of rows in the range.
This is for a data query on number of report checked in.
Dim range1 As Range
Set range1 = Sheet1.Range("B3 : B" & Cells(Rows.Count)).End(xlUp).Rows
The result should be a range B3:B46 or whatever the end row number is.
回答1:
Try this:
Dim cell As Range
For Each cell In Sheet1.Range("B3:B" & Sheet1.Cells(Sheet1.Rows.count, 2).End(xlUp).Row)
'Do your stuff
Next cell
回答2:
Another way to do it that will give you the last row that has data in it:
Option Explicit
Sub RowCount()
Dim WS As Worksheet
Dim lrow As Long
Set WS = ActiveSheet
With WS
lrow = .Range("B" & .Rows.Count).End(xlUp).Row - 2
End With
End Sub
回答3:
Try this
Dim range1 As Range
Dim x as long
With Sheet1
x= .Cells(.rows.Count, 2).End(xlUp).Row
Set range1 = .Range("B3", .Cells(x,2))
End with
回答4:
Simplest way is to use the .End(xlUp) property.
Dim rng as Range: Set rng = Sheet1.Range("B3:B" & Sheet1.Cells(Rows.Count, 2).End(xlUp).Row)
Now you have B3:B<last_row> stored in the variable rng
来源:https://stackoverflow.com/questions/55976426/counting-a-range-rows-begingin-in-b3