Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first and last row containing specific text

Tags:

excel

vba

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.

like image 900
BruceWayne Avatar asked Mar 12 '15 20:03

BruceWayne


People also ask

How do I find the last row that contains data in Excel?

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.

How do I select the first and last cell of data in Excel?

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.

How do you find the first cell with value in Excel VBA?

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.


2 Answers

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.

like image 85
BruceWayne Avatar answered Oct 14 '22 01:10

BruceWayne


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.

like image 38
IAWeir Avatar answered Oct 14 '22 00:10

IAWeir