Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MsgBox never displayed after for loop 1

Status
Not open for further replies.

sidalam

Programmer
Nov 21, 2003
94
I am using the code below to find a student in an Excel spreadsheet however why does MsgBox("Name not found") ever get displayed. The code searches for a name in cells A4 to A14.

Private Sub CommandButton1_Click()
Dim findname As String
Dim counter As Integer
Dim cellRange As String
findname = InputBox("Enter student name")
For counter = 4 To 15
cellRange = "A" & counter
If Range(cellRange).Value = findname Then Exit For
Next counter
If counter = 15 Then
MsgBox ("Name not found")
Else
MsgBox ("Found at " & cellRange)
End If

End Sub
 

In your code:
Code:
For counter = 4 To 15
    cellRange = "A" & counter
    If Range(cellRange).Value = findname Then Exit For
Next counter
[green]
'Outside of your For loop your variable [red]counter = 16[/red][/green]

If counter = 15 Then
    MsgBox ("Name not found")
Else
    MsgBox ("Found at " & cellRange)
End If

Have fun.

---- Andy
 
Thanks Andrzejek

What is a quick way to check the output of a loop?
For example could I write to the console or text file for test purposes because my head always gets lost in loops for more complex code?
 

I don't know what you mean by "What is a quick way to check the output of a loop?"

You can change you code a little:
Code:
Dim bln As Boolean
bln = False

For counter = 4 To 15
    cellRange = "A" & counter
    If Range(cellRange).Value = findname Then 
        MsgBox ("Found at " & cellRange)
        bln = True
        Exit For
    End If
Next counter

If bln = False Then
    MsgBox ("Name not found")
End If
What do you want to write inot a text file?

Have fun.

---- Andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top