Excel VBA功能-检查字符串中的数字是否大于字母

Joa*_*lai 0 excel vba

我正在使用此功能来测试字符串是否包含数字。但是,我需要以某种方式对其进行修改,以检查字符串是否实际上具有比字母更多的数字。

Function HasNumber(strData As String) As Boolean
    Dim iCnt As Integer

    For iCnt = 1 To Len(strData)
        If IsNumeric(Mid(strData, iCnt, 1)) Then
            HasNumber = True
            Exit Function
        End If
    Next iCnt

End Function
Run Code Online (Sandbox Code Playgroud)

chi*_*lin 6

我认为这些功能之一应该可以满足您的需求。它们之间的唯一区别是它们认为的“字母”。

Option Explicit

Private Function MoreNumbersThanLetters(ByVal someTextToCheck As String) As Boolean
    ' "Letters" in the context of this function = "a-z,A-Z"
    ' as opposed to "anything that's not a number".
    ' This means this function ignores symbols (non-numeric, non-alphabetical characters)

    Dim countOfLetters As Long
    Dim countOfNumbers As Long

    Dim characterIndex As Long
    For characterIndex = 1 To Len(someTextToCheck)
        Select Case Asc(Mid$(someTextToCheck, characterIndex, 1))
            Case 65 To 90, 97 To 122 ' A-Z, a-z
                countOfLetters = countOfLetters + 1
            Case 48 To 57 ' 0-9
                countOfNumbers = countOfNumbers + 1
        End Select
    Next characterIndex

    MoreNumbersThanLetters = countOfNumbers > countOfLetters
End Function

Private Function MoreNumbersThanLetters(ByVal someTextToCheck As String) As Boolean
    ' "Letters" in the context of this function = "anything not a number",
    ' so this function consider symbols as letters too.

    Dim countOfNumbers As Long

    Dim characterIndex As Long
    For characterIndex = 1 To Len(someTextToCheck)
        If IsNumeric(Mid$(someTextoCheck, characterIndex, 1)) Then
            countOfNumbers = countOfNumbers + 1
        End If
    Next characterIndex

    MoreNumbersThanLetters = (countOfNumbers / Len(someTextToCheck)) > 0.5

End Function
Run Code Online (Sandbox Code Playgroud)