I have a long (2,000 + rows) list of different values. I am trying to find the first and last row for each value. As an example (note: all data is in one column):
Bats
Bats
Bats
Bats
Bats
Bats
Fun
Fun
Fun
Fun
Bases
Bases
Bases
Bases
Bases
Bases
Bases
Bases
Bases
Bases
Bases
Balls
Balls
Balls
Balls
Balls
Balls
Balls
Balls
How do I find the first row (starting at the top) and last row containing each word. "Bats" starts row 1, ends at row 6. "Fun" starts row 7, ends at row 10.
Any ideas for a quicker way to do this, other than a loop where I compare each cell to the previous, and add a row variable if they're different?
Looking for how to do so in VBA.
Locate the last cell that contains data or formatting on a worksheet. To locate the last cell that contains data or formatting, click anywhere in the worksheet, and then press CTRL+END.
Use Ctrl + Shift + arrow key (out of 4 arrow keys) to select the cells while traversing through data. Select cells and ranges to use it in as arguments in formulas using this shortcut. Hope this article about using Shortcut to jump to the last cell and first cell in Excel is explanatory.
Find method in VBA. In this case, we will use the Range. Find method to start in the last cell in the worksheet, and set the SearchDirection parameter to xlNext . This then starts the search in the first cell in the worksheet (A1) and looks through each row until a non-blank cell is found.
I figured it out - VBA style. I can just use find() to help out:
Dim batStartRow as Long, batEndRow as Long
With Sheets("Sheet1")
batStartRow = .Range("A:A").Find(what:="bats", after:=.Range("A1")).Row
batEndRow = .Range("A:A").Find(what:="bats",after:=.Range("A1"), searchdirection:=xlPrevious).Row
End With
Then replace "bats" with the other words, and it'll work.
Edit: You may need to add the LookIn:=xlValues
qualifier too, depending on the info/data being searched.
if the values are already grouped you can use the following to find the first Row occurrence
=MATCH("Bats",A:A,0)
and this to find the last Row occurrence
=(MATCH("Bats",A:A,0)+(COUNTIF(A:A,"Bats"))-1)
and substitute "Bats" with each distinct Value you want to look up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With