Regex 使正则表达式与主题代码匹配
我在excel中有一些主题代码。在一个单元中将有3个病例。我使用VBA来处理以下内容Regex 使正则表达式与主题代码匹配,regex,excel,vba,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 / ......... 目前,我的意图是,如
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......
这超出了我的能力,所以我需要一些帮助。我想你必须先理解你的语法,才能找出可能的错误。如果我理解你的意思是正确的:
- 表达式中有两个不同的运算符,但这是不允许的
把它们混合在一起。运算符是
和+
(除此之外)/
- 除了这些操作符之外的任何东西都被视为术语
- 一个空格分隔术语
- 如果有多个术语,则术语必须由运算符分隔李>
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
如果用户每次更改单元格(即验证其输入)时都执行代码,则不确定是否有有效的方法来执行此操作 您可以使用与工作表更改事件关联的构造,该事件遵循以下内容:
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而不是regex
你可以浓缩成一个精选的案例
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
您好,请问我如何将excel函数嵌入到整个列中。这也适用于用户将要输入的未来列?嗨,您的注释是要在@FunThomas的响应下面吗?实际上,对于你们两个来说。1)vba:应用函数从开始行循环到结束行,或者2)在要测试其值的相邻列中,在每个单元格上放置公式=testSyntax。应在开始键入时显示。函数返回一个布尔值(true false),如果单元格为空则退出。您需要修改所需的msgbox,如果testSyntax=false,则可能需要修改msgbox“msg”。另外,考虑一下你的空白细胞测试条件,因为细胞可能会开始空白。好。我会给它一个测试