如何在文本框 vba 中输入 1 位或 2 位小数后自动制表?

How to autotab after input of 1 or 2 decimal places in textbox vba?

我想在输入一个小数点后一位的值后将焦点移到下一个文本框,例如。 “123.4”,如果输入的值是文本,它也不应该移动,例如。 “abc.e”。有什么办法吗?

是的,你可以。您可以使用 Regular Expressions.

'needs reference to MS VBScript Regular Expressions 5.5
Private Sub TextBox1_Change()
    Dim spattern As String, sText As String
    Dim r As RegExp
    Dim bResult As Boolean
    
    If Len(TextBox1.Text) < 3 Then Exit Sub
    
    sText = TextBox1.Text
    'define pattern
    spattern = "\d{1,}" & Application.DecimalSeparator & "\d{1,2}"
    Set r = New RegExp
    With r
        .pattern = spattern
        bResult = .Test(sText)
    End With
    
    If bResult Then
        'move focus to the next control
    End If
End Sub

我认为您的 objective 与自动跳格无关,而是限制文本框中的输入。如果这是真的,那么这可能会有所帮助。

您可以使用 KeyPress 事件限制在文本框中按下的键。除了导航之外,下面的代码将允许 ONLY 数字和小数。

这是你正在尝试的吗?不需要任何工作参考

Option Explicit

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyDelete, _
             vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
            If KeyAscii = 46 Then If InStr(1, TextBox1.Text, ".") Then KeyAscii = 0
        Case Else
            KeyAscii = 0
            Beep
    End Select
End Sub

如果您仍然需要自动制表符,那么也可以在这里处理。

请测试下一段代码:

Private Sub TextBox1_Change()
 If Len(Me.TextBox1.Text) >= 3 Then
    If IsNumeric(Me.TextBox1.Text) And _
            Right(Me.TextBox1.Text, 3) Like "#.#" Then
       'controlX.SetFocus
       'Me.txtTest.SetFocus
    End If
 End If
End Sub

我认为将它与@Siddharth Rout 发布的上述事件(不允许数字以外的其他字符)一起使用应该是您的完美解决方案。在这种情况下,IsNumeric(...) 检查可能会丢失。

如果你需要让它允许两位小数,将“#.#”替换为“#.##”并使Len(...) >= 4等就可以了...