Logo 
Search:

MS Office Answers

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds
  Question Asked By: John Cooper   on Oct 19 In MS Office Category.

  
Question Answered By: Shirley Allen   on Oct 19

It looks like you've combined techniques from more than one source and haven't
cleaned it up.
Let's take a look at what you're doing:
Sub FindName()
Dim found  = Cells.Find (What:=LookFor)

Why are you DECLARING "Found" to be the result  of the find  method, then later
doing it again? Also, at this point, "LookFor" has no value.
I suggest changing the line to: Dim Found


Dim ws As Worksheet, LookFor As Variant 'Declaring Variables
LookFor = InputBox("Enter name to find") 'Prompting user  for name
If LookFor = "" Then exit  Sub ' If no name is supplied, exit
sub.
For Each ws In ActiveWorkbook.Worksheets 'Loop through all worksheets in
workbook
Set Found = ws.Cells.Find( what:=LookFor) 'Look for string on worksheet
If Not Found Is Nothing Then Exit For 'If string is found, stop
looking
Next ws '(end of worksheet
loop)
If Found Is Nothing Then ' If string is not found,
then issue message
MsgBox LookFor & " not found.", vbExclamation
Now, the next few lines get confusing.
You have TWO "else" statements, which should have caused a compiler error.
The findNext method is confusing here because you've gone to all the trouble to
find
the FIRST ocurrence of the string, then you're saying, "ok, skip that one and
take me to
the NEXT ocurrence". I suspect that these next two lines need to me removed.
Else
Cells.FindNext( After:=ActiveCell).Activate

Else
Application.Goto reference:=Found, scroll:=True 'This is the line that will
take you to the cell.
End If
End Sub

Now, if we clean up the code  you end up with:
'----------------------------------------------------------------
Option Explicit
Sub FindName()
Dim Found, ws As Worksheet, LookFor As Variant
LookFor = InputBox("Enter name to find")
If LookFor = "" Then Exit Sub
For Each ws In ActiveWorkbook.Worksheets
Set Found = ws.Cells.Find(What:=LookFor)
If Not Found Is Nothing Then Exit For
Next ws
If Found Is Nothing Then
MsgBox LookFor & " not found.", vbExclamation
Else
Application.Goto reference:=Found, Scroll:=True
End If
End Sub
'----------------------------------------------------------------
which seems to work.
Hope this helps.

Share: 

 

This Question has 4 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on inputbox macro help Or get search suggestion and latest updates.


Tagged: