使正则表达式匹配主题代码

时间:2017-10-02 12:05:10

标签: regex excel vba

我在excel中有一些主题代码。单个细胞中将有3个病例。我正在使用VBA处理以下内容。

Case 1: Single subject in a cell

ABC1000

Case 2: Multiple "And" subjects in a cell

ABC1000 + 1234 + CJ43 + ......

Case 3: Multiple "Or" subjects in a cell

ABC1000 / BlaAdc / CJ43 / .........

目前,我的意图是如果有人在单元格中输入以下无效案例。将弹出错误消息框。

* ABC1000 + + bla200
* ABC1000 + bla200 / CJ43
* Nothing in the cell
* ABC1000 & bla200
* ABC1000 && bla200
* ABC1000 OR bla200
* ABC1000 or bla200
* Criminology 301
* And more......

它超出了我的能力所以我需要一些帮助。

2 个答案:

答案 0 :(得分:1)

如果您在每次用户对单元格进行更改(即验证其输入)时执行代码,则不确定执行此操作的有效方法。

您可以使用绑定到工作表更改事件的构造:

myStr = target.Value   'e.g. "ABC1000 + + bla200"

If myStr = "" Then MsgBox "Invalid entry"

If InStr(1, myStr, " ") > 0 Then MsgBox "Invalid entry"

If InStr(1, myStr, "+") > 0 And InStr(1, myStr, "\") > 0 Then MsgBox "Invalid entry"

If InStr(1, myStr, "++") > 0 Then MsgBox "Invalid entry"

If InStr(1, myStr, "&") > 0 Then MsgBox "Invalid entry"

If InStr(1, myStr, "&&") > 0 Then MsgBox "Invalid entry"

您将构建测试条件列表并使用InStr而不是正则表达式。

您可以将其浓缩为精选案例

Select Case True
Case InStr(1, myStr, "+") > 0 And InStr(1, myStr, "\") > 0, myStr = vbNullString, InStr(1, myStr, " ") > 0, _
     InStr(1, myStr, "++") > 0, InStr(1, myStr, "&") > 0, InStr(1, myStr, "&&") > 0
    MsgBox "Invalid entry"
End Select

答案 1 :(得分:0)

我认为您必须首先理解您的语法,以确定可能的错误。如果我理解你的错误:

  • 您的表达式中有两个不同的运算符,但不允许这样做 把它们混合在一起。运营商是+/(没有别的)
  • 除了这些运营商之外的任何东西都被视为条款。
  • 空白分割条款。
  • 如果您的术语不止一个,则术语必须由运营商分隔。

我不会尝试用正则表达式来解决这个问题,但是使用UDF。我玩了一下,这是我的尝试:

Function testSyntax(inputStr As String) As Boolean
Const OperatorOR = "/"
Const OperatorAND = "+"

testSyntax = False
Dim s As String, orParts() As String, andParts() As String
s = Trim(inputStr)
If s = "" Then Exit Function     ' Empty string

' split parts
orParts = Split(s, OperatorOR)
andParts = Split(s, OperatorAND)

If UBound(orParts) > 0 And UBound(andParts) > 0 Then Exit Function  ' mixed operators
Dim i As Integer, p As String
If UBound(orParts) > 0 Then
    ' Or-operator used.
    For i = 0 To UBound(orParts)
        p = Trim(orParts(i))
        If p = "" Or InStr(p, " ") > 0 Or InStr(p, vbTab) > 0 Then Exit Function   ' 2 terms or 2 OR operators in row
    Next i
Else
    ' And-operator used (or only 1 term)
    For i = 0 To UBound(andParts)
        p = Trim(andParts(i))
        If p = "" Or InStr(p, " ") > 0 Or InStr(p, vbTab) > 0 Then Exit Function   ' 2 terms or 2 AND operators in row
    Next i
End If
testSyntax = True

End Function