将Regex应用于VBA的文本框形式

时间:2017-01-25 17:00:34

标签: regex excel vba textbox

我需要你的帮助。如何限制文本框?这是我的表格。 enter image description here

我需要为以下文本框创建if语句: 托盘ID:必须仅包含9个数字 纸箱ID:必须只包含10个数字 序列号(全部6个):必须以FOC开头且仅包含CAPS和数字[A-Z] [0-9]

我在Javascript中这样做但现在我需要在excelsheet中备份。有什么想法吗?

感谢您的关注,

1 个答案:

答案 0 :(得分:2)

我创建了一个样本User_Form和一个CommandButton(就像一个“确认”按钮),一旦按下它,它会检查TextBox es中输入的所有值是否符合要求遵守规则。

以下代码将帮助您入门,它会检查“托盘ID”(9位数)和“纸箱ID”(10位数)中的值。

<强>代码

Option Explicit

Private Sub CommandButton1_Click()

Dim Reg1 As Object
Dim Reg2 As Object

Dim RegMatches As Object

' ====== Test PalletID_Tb =====
Set Reg1 = CreateObject("VBScript.RegExp")
With Reg1
    .Global = True
    .IgnoreCase = True
    .Pattern = "\d{9,9}" ' Match any set of 9 digits
End With

Set RegMatches = Reg1.Execute(Me.PalletID_Tb.Value)

If RegMatches.Count = 1 Then '<-- make sure there is only 1 match (9 digits and not 18 or 27)
    MsgBox "Value in Pallet ID is OK"
Else
    MsgBox "Pallet ID must have a 9 digit format"
    Me.PalletID_Tb.Value = ""
    Exit Sub
End If

' ====== Test CartonID_Tb =====
Set Reg2 = CreateObject("VBScript.RegExp")
With Reg2
    .Global = True
    .IgnoreCase = True
    .Pattern = "\d{10,10}" ' Match any set of 10 digits
End With

Set RegMatches = Reg2.Execute(Me.CartonID_Tb.Value)

If RegMatches.Count = 1 Then '<-- make sure there is only 1 match (10 digits and not 20)
    MsgBox "Value in Carton ID is OK"
Else
    MsgBox "Carton ID must have a 10 digit format"
    Me.CartonID_Tb.Value = ""
    Exit Sub
End If

' Do something if passed the 2 conditions

End Sub