简体   繁体   English

在Excel VBA中的字符串中查找数字

[英]Finding a number in a string in excel VBA

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. 我试图在excel vba中通过文本框提供的字符串中找到一个数字,并显示一条错误消息,指出它无法继续,此后必须停止加载下面的代码。

fname is Full Name given by the user fname是用户指定的全名

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) 如果它包含一个数字(数字列表),则应该搜索用户给出的文本并显示错误

InStr function is not boolean, it returns integer value. InStr函数不是布尔值,它返回整数值。 It will give you nth number of the string(fname), if your searching expression(for example "0") is inside string(fname). 如果您的搜索表达式(例如“ 0”)在string(fname)内,它将为您提供字符串(fname)的第n个数字。 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

Maybe a simple answer, but Cstr() changes integers into strings. 也许是一个简单的答案,但是Cstr()将整数更改为字符串。

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

无需循环,只需一行即可完成:

If Fname like "*[0-9]*" Then MsgBox ("Number Found In Your Name. Please Correct That!!")

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM