将正则表达式应用到文本框中VBA

将正则表达式应用到文本框中VBA

问题描述:

我需要你的帮助。我怎样才能限制我的文本框?这是我的下面的表单。 enter image description here将正则表达式应用到文本框中VBA

我需要的是创造,如果下列文本框声明: 托盘ID:必须只包含9号 纸箱ID:只能包含10个号码 连续剧(全6):必须startwith FOC和仅包含CAPS和数字[AZ] [0-9]

我在Javascript中做了这个,但现在我需要在excelsheet中有一个备份。有任何想法吗?

感谢您的关注,

+1

设置每个框'MaxLength'财产,并处理文本框的事件,例如'txtPalletID_KeyDown'如果你想截取单个的键(并且实际上*防止*它们甚至被输入到第一个位置),或者'txtPalletID_Exit'在焦点切换到另一个控件时验证内容(并且可能取消它并强制重新回到文本框中);通过这种方式,您可以禁用“Agregar”按钮,直到所有字段被认为是有效的......但是这对于单个SO问题来说是相当广泛的主题。尝试一下,卡住,回来*特定*问题=) –

+1

让我试试看:) – Deluq

+0

@Deluq阅读我的答案和代码 –

心中已经创建了一个示例User_FormCommandButton(如“确认”按钮),一旦它按下它会检查在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 
+0

谢谢你的时间! – Deluq