Check if string contains a number

  • I am trying to check if a user entered string contains a number in it. If it does i want to create an error. What is a simple way of doing this?

  • Re: Check if string contains a number


    Thanks Dave but i found something i could use



    Code
    If HasNumber(fgncurrency) = True Then
        Err = 1
    End If


    then


  • Re: Check if string contains a number


    Here's where a little bit of Linq can make life easier. This will return a boolean telling if there's at least one numeric character in the string.

    (from items in inputString.ToCharArray Where Char.IsDigit(items)).Count <> 0


    Dave

  • Re: Check if string contains a number




    Thanks grays - this is super helpful.


    However, is there a way to modify it to be true if it contains any number except 0?


  • Hi Dave, I hope you get this... 7 years later


    Could you elaborate on how your code is supposed to work? I can't seem to make it work?



    from items in inputString.ToCharArray WhereChar.IsDigit(items)).Count <> 0


    how do i write this?


    ie: x = from items in inputString.ToCharArray WhereChar.IsDigit(items)).Count <> 0 ??

  • LINQ doesn't work in VBA as far as I know. Seems overkill here anyway when a simple Like operator will work:


    Code
    Function HasNumber(sIn As String) As Boolean
        HasNumber = sIn Like "*#*"
    End Function
    Function HasNumberOtherThanZero(sIn As String) As Boolean
        HasNumberOtherThanZero = sIn Like "*[1-9]*"
    End Function

    Rory
    Theory is when you know something, but it doesn’t work. Practice is when something works, but you don’t know why. Programmers combine theory and practice: nothing works and they don’t know why

  • LINQ doesn't work in VBA as far as I know. Seems overkill here anyway when a simple Like operator will work:


    Code
    Function HasNumber(sIn As String) As Boolean
    HasNumber = sIn Like "*#*"
    End Function
    Function HasNumberOtherThanZero(sIn As String) As Boolean
    HasNumberOtherThanZero = sIn Like "*[1-9]*"
    End Function


    You're absolutely right ! Works like a charm. So simple yet so efficient.


    Thanks rory !

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!