【问题标题】:How to force the input of a textbox on a userform to be a specific format in VBA如何强制用户窗体上的文本框输入成为 VBA 中的特定格式
【发布时间】:2016-08-03 15:29:33
【问题描述】:

我有一个带有一系列输入文本框的用户表单,我正在寻找一种方法来防止用户输入除 5 位数字后跟一个字母后跟 4 位数字以外的任何内容。例如。 12345A6789

我可以看到一种只使用数字和字母的方法,并创建三个文本框,然后以某种方式将它们全部合并在一起——尽管也不知道如何做到这一点。理想情况下,只有一个文本框。

感谢任何帮助

【问题讨论】:

  • 可以编写一个 onchange 处理程序来主动检查输入是否符合您期望的格式。
  • 如果您从不需要代码在 Mac 上工作,您可以使用正则表达式。代码没有 mac 兼容性,你还好吗?
  • 更好的标题。文字小改动。
  • 该文档将发送给很多人,因此其中一些人可能是 mac 用户。

标签: vba input textbox controls


【解决方案1】:

内置Textbox在这个部门有点欠缺。我解决这个问题的方法是使用Change 事件来强制格式化。请注意,Key* 事件不会处理将文本放入文本框的任何其他方式(拖放、复制粘贴等)。类似这样的东西(这是用于 zip + 4,但类似的概念也可以):

Private Sub TextBox1_Change()
    Static reentry As Boolean                           'anti-recursion flag
    If reentry Then Exit Sub
    Dim chars() As Byte
    chars = StrConv(TextBox1.Text, vbFromUnicode)

    Dim buffer As String
    Dim i As Integer
    For i = LBound(chars) To UBound(chars)
        If Len(buffer) = 5 Then buffer = buffer & "-"   'auto-insert the dash
        If Len(buffer) = 10 Then Exit For               'limit to 10 chars
        If chars(i) >= 48 And chars(i) <= 57 Then       'ignore anything but numbers.
            buffer = buffer & Chr$(chars(i))
        End If
    Next i

    reentry = True
    TextBox1.Text = buffer
    reentry = False
End Sub

【讨论】:

  • 这真的很有帮助,谢谢,我已经得到了我需要的大部分内容,但是我需要字符后面的条目是字母而不是数字,因此使用忽略除数字之外的任何内容都不起作用我的情况。
【解决方案2】:

我想出了一个可以正常工作的解决方案,我确信这可以改进以防止用户输入特殊字符,但这足以减少大多数错误

'Checks that document number is the correct format (5 digits, 1 letter, 4 digits)
Sub TextBox_DocumentNumber_AfterUpdate()

If (IsNumeric(Left(TextBox_DocumentNumber, 5))) = False Then
Call DocumentNumberFormat


ElseIf (IsNumeric(Mid(TextBox_DocumentNumber, 7))) = True Then
Call DocumentNumberFormat


ElseIf (IsNumeric(Right(TextBox_DocumentNumber, 4))) = False Then
Call DocumentNumberFormat

End If

End Sub



Sub DocumentNumberFormat()

Dim DocNum As String
Dim Response As VbMsgBoxResult

DocNum = MsgBox("Please enter document numbers in the formart 00000-A-0000", vbRetryCancel + vbExclamation, "Incorrect Format")


UserForm3.TextBox_DocumentNumber = ""
If DocNum = vbCancel Then
           Call Cancel
End If

Exit Sub
End Sub





'Auto inserts hyphens and sets max length for document number
Private Sub TextBox_DocumentNumber_Change()
If Len(TextBox_DocumentNumber) = 5 Then TextBox_DocumentNumber = TextBox_DocumentNumber & "-"
If Len(TextBox_DocumentNumber) = 7 Then TextBox_DocumentNumber = TextBox_DocumentNumber & "-"
TextBox_DocumentNumber.MaxLength = 12
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2021-12-18
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多