首页 > 解决方案 > VBA isString vs isNumeric

问题描述

我正在验证 Excel 中 VB 用户窗体中某些文本框中的数据。

数据可以是 6 位长的数字、至少 3 个字符长的字符串或字符串和数字的组合。

为此,我写道:

If Len(Trim(Me.TextBox1)) = 6 And IsNumeric(Trim(Me.TextBox1)) Then
  (do operation)
Elseif Len(Trim(Me.TextBox1)) > 2 and IsString(Trim(Me.TextBox1)) Then
  (do another operation)
Else
  (do third operation)
End if

我可以让它工作isNumeric,但似乎 VBA 不支持isString

有没有聪明的办法来解决这个问题?

标签: excelvba

解决方案


您可以调用工作表函数

Application.WorksheetFunction.IsText

不过,我可能会更自在地走线并使用 AscW 进行测试,如果期望 A-Za-z 则查找 65-90 和 95-122 范围内的值。

您绝对可以在以下方面进行改进。您可以参考ascii 代码来确定构成文本的可接受值。另请注意,网络上有大量功能可用于执行此任务。

 Public Sub test()
    Dim s As String, i As Long
    s = "pr81"
    For i = 1 To Len(s)                          ' 65-90 and 95-122.
        Select Case True
        Case (AscW(Mid$(s, i, 1)) >= 65 And AscW(Mid$(s, i, 1)) <= 90) Or _
             (AscW(Mid$(s, i, 1)) >= 95 And AscW(Mid$(s, i, 1)) <= 122)
        Case Else
            MsgBox "Values are not all in range A-Za-z"
            Exit For
        End Select
    Next i
End Sub

感谢@DirkReichel,这是一个非常简化的测试:

Option Explicit
Public Sub test()
    Dim s As String, i As Long
    s = "pr81"
    For i = 1 To Len(s)
        If LCase(Mid$(s, i, 1)) = UCase(Mid$(s, i, 1)) Then
            MsgBox "Not all letters"
            Exit For
        End If
    Next i
End Sub

推荐阅读