PDA

View Full Version : Very Basic Loop Question?



Pajo
03-29-2009, 12:48 PM
Hi, I'm new to excel VBA. I have a very basic question in relation to loops. I am looping through a column to search each cell for a certain string. How can I construct a loop in order for it to exit if the search string is not there - and avoid an overflow error. An example of my code is below.

Do

j = j + 1

Loop Until WorkSheet1.Cells(j, 1) = Searchstring


Any help would be greatly appreciated....

Kenneth Hobs
03-29-2009, 01:44 PM
Welcome to the forum!

Find would be a better route. e.g.
Sub t()
Dim objFind As Range
Dim objSheet As Worksheet
Dim strRange As String

[a1] = "whatever"
[a2] = "something else"
[a3] = "C:\foo\foo\foo\myfile.doc"
[a4] = "end"
strRange = "A:A"
Set objSheet = ActiveSheet

Set objFind = objSheet.Range(strRange).Find(what:="*myfile.doc", _
LookIn:=xlFormulas, lookat:=xlWhole, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, MatchCase:=False)

If Not objFind Is Nothing Then MsgBox objFind.Address
End Sub

Pajo
03-29-2009, 03:04 PM
Kenneth, many thanks for the response. I wrote the loop in order to find the row number of the specific text (which is always a simple string) that I needed. Can this code return the row number?

Kenneth Hobs
03-29-2009, 03:09 PM
The object found is a Range so you can use:
If Not objFind Is Nothing Then MsgBox objFind.Row

Pajo
03-29-2009, 03:46 PM
That's great...thanks for that