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

时间:2019-06-09 09:46:06

标签: 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这可能有用:

Option Explicit

Sub test()

    Dim NumNo As Long: NumNo = 0
    Dim LettNo As Long: LettNo = 0
    Dim i As Long

    Dim str As String

    With ThisWorkbook.Worksheets("Sheet1")

        str = .Range("A1").Value

        For i = 1 To Len(str)

            If IsNumeric(Mid(str, i, 1)) Then
                NumNo = NumNo + 1
            Else
                LettNo = LettNo + 1
            End If

        Next i

    End With

    If NumNo > LettNo Then
        MsgBox "More numbers than letters"
    ElseIf NumNo < LettNo Then
        MsgBox "Less numbers than letters"
    ElseIf NumNo = LettNo Then
        MsgBox "Equal number of numbers and letters"
    End If

End Sub