简体   繁体   English

检查数组中是否包含非数字字符

[英]Check an array for non-numeric characters

I am trying to create a function that will check an array for non-numeric characters. 我正在尝试创建一个将检查数组中非数字字符的函数。 I'm sure there is a way with existing functions, but I was hoping to make a clean function. 我敢肯定现有功能有一种方法,但是我希望做一个干净的功能。

This is what I have: 这就是我所拥有的:

Public Function ContainsAllNumbers(Text() As Variant) As Boolean

    For Each element In Text

        If Not IsNumeric(element) Then

            ContainsAllNumbers = False

        End If

    Next

End Function

The arguments I want it to take would be something like 11013688 or K03778 or 9005110-4400. 我希望它接受的参数应该是11013688或K03778或9005110-4400。 I need to know if these strings contain something that is not a number. 我需要知道这些字符串是否包含不是数字的东西。

I assume you want a function that takes an array of strings and checks them for nun-numeric values. 我假设您想要一个函数,该函数需要一个字符串数组并检查它们的非数字值。 Then your question would be, why your function always returns False . 那么您的问题将是,为什么您的函数总是返回False

The default value of a Boolean is false so you need to set ContainsAllNumbers = True at the beginning of the function. Boolean值的默认值为false,因此您需要在函数开始时设置ContainsAllNumbers = True

I also recommend using Option Explicit so you don't forget to Dim your variables. 我还建议您使用Option Explicit这样您就不会忘记对变量进行调Dim

Here is a (debugged) function which takes a string input and returns True if and only if all of the characters in the string are digits. 这是一个(调试的)函数,该函数接受字符串输入,并且仅当字符串中的所有字符均为数字时,才返回True This is (perhaps) what you are trying to do: 这是(也许)您正在尝试做的事情:

Function AllDigits(s As String) As Boolean
    Dim i As Long
    For i = 1 To Len(s)
        If Not IsNumeric(Mid(s, i, 1)) Then
            AllDigits = False
            Exit Function
        End If
    Next i
    AllDigits = True
End Function

Convert the characters to their ascii code and check each of them. 将字符转换为它们的ascii代码并检查每个字符。 You can Look up an ascii table to find out the specific values for certain characters. 您可以查找一个ascii表以找出某些字符的特定值。

As an example I just copied this from one of my macros. 例如,我只是从我的一个宏中复制了此代码。 It checks for non-alphanumeric values in the input string str: 它检查输入字符串str中的非字母数字值:

invalidCharacter = false
For pos = 1 To Len(str) 
Select Case Asc(Mid(str, pos, 1)) 'ascii value of character at str(pos)
        Case 48 To 57, 65 To 90, 97 To 122 '0-9,a-z,A-Z
            'nothing
        Case Else
            invalidCharacter = True
    End Select
Next pos
If invalidCharacter Then
    MsgBox "only numbers or letters may be used"
End If

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

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