Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find text in a column and saving the row number where it is first found - Excel VBA

Tags:

excel

vba

I have the following column (column A) named project (rows column is just displaying the row number):

rows    project
1       14
2       15
3       16
4       17
5       18
6       19
7       ProjTemp
8       ProjTemp
9       ProjTemp

I have an input message box where the user writes the new project name which I want inserted right after the last one. Ex: project 20 will be inserted right after project 19 and before the first "ProjTemp".

My theory was to locate the row number of the first "ProjTemp" and then insert a new row where the project is 20.

I was trying to use the Find function but I'm getting an overflow error (I'm sure I'm getting it because it's finding 3 "ProjTemp" strings and trying to set it to one parameter):

Dim FindRow as Range

with WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        MatchCase:=False)
end with

How do I code this so I only find the row number of the fist "ProjTemp"? Is there a better way to do this, maybe a loop?

Thanks, any help will be appreciated!

like image 734
Kristina Avatar asked Apr 09 '13 19:04

Kristina


People also ask

How do you find a text in a row in Excel VBA?

To find a cell with a numeric value in an Excel Table, set the SearchOrder parameter to either of the following, as applicable: xlByRows (SearchOrder:=xlByRows): To search by rows. xlByColumns (SearchOrder:=xlByColumns): To search by columns.

How do I use find in Excel VBA?

Formula to Find Function in Excel VBA. In regular excel worksheet, we simply type shortcut key Ctrl + F to find the contents.


1 Answers

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row
like image 87
mango Avatar answered Nov 16 '22 00:11

mango