1

I am trying to find a number in a string given via textbox in excel vba and display an error saying it cant continue and after that it must stop from loading the codes below.

fname is Full Name given by the user

If InStr(fname, "0") Then
    MsgBox ("Number Found In Your Name. Please Correct That!!")

 Dim i(0 To 9) As String
    i(0) = "0"
    i(1) = "1"
    i(2) = "2"
    i(3) = "3"
    i(4) = "4"
    i(5) = "5"
    i(6) = "6"
    i(7) = "7"
    i(8) = "8"
    i(9) = "9"


If InStr(fname, "0") Then
    MsgBox ("Number Found In Your Name. Please Correct That!!")

End If

It is supposed to search in the text given by the user and display an error if it contains a number(list of numbers)

5 Answers 5

2

No loop needed, it can be done with one line:

If Fname like "*[0-9]*" Then MsgBox ("Number Found In Your Name. Please Correct That!!")
Sign up to request clarification or add additional context in comments.

Comments

1

InStr function is not boolean, it returns integer value. It will give you nth number of the string(fname), if your searching expression(for example "0") is inside string(fname). Otherwise, it returns zero. So, you can try your code like this:

For i=0 to 9
    If InStr(fname, i)>0 Then
        MsgBox ("Number Found In Your Name. Please Correct That!!")
    End If
Next i

2 Comments

Can it stop loading the codes below it? That's what I need now.
I tried doing this, and it runs code inside If everytime. it does not have anything to check.
1

Maybe a simple answer, but Cstr() changes integers into strings.

For i = 0 To 9
    If InStr(fname, CStr(i)) Then
        MsgBox ("Number Found In Your Name. Please Correct That!!")
        Exit For
    End If
Next

3 Comments

I'm not sure what you mean. But you can replace the code you posted with the one in the answers.
after it displays the error message, it shouldn't run the lines of code below it.
I think I understand. There is more code below this part. If you change Exit For into Exit Sub it should work.
0

Regex is the best way, but a loop can also work:

Sub dural()
    Dim s As String, i As Long
    s = "james"
    For i = 0 To 9
        If InStr(1, s, CStr(i)) > 0 Then
            MsgBox ("Number Found In Your Name. Please Correct That!!")
            Exit Sub
        End If
    Next i
End Sub

Comments

0

You could try implement `EVALUATE'

If Evaluate("COUNT(FIND(ROW(1:10)-1,""" & fname & """))") > 0 then
    Msgbox "Number Found In Your Name. Please Correct That!!"
End if

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.