我想知道是否可以使用一些VBA在一大堆5char字符串中查找定义的模式?我已经探索了“instr”函数但是我不确定它是否会执行我需要的任务,这基本上是在字符串中查找模式,如下所示;
ABABA
BCBCB
.....
EFEFE
或者任何第一个字符与字符3和字母3相同的模式。 5,第2个字符与char 4相同。
感谢任何帮助或指示。
亲切的问候
吉姆
答案 0 :(得分:1)
你可以在没有VBA的情况下做到这一点,它仍然足够快:
=IF(AND(MID("ABABA",1,1)=MID("ABABA",3,1),MID("ABABA",2,1)=MID("ABABA",4,1),MID("ABABA",3,1)=MID("ABABA",5,1)),1,0)
只需更换" ABABA"与相应的单元格地址及其相关
答案 1 :(得分:1)
尝试使用Like
运算符:
Const testString = "ABABA"
Dim myChar1 As String, myChar2 As String
'// test 1/3/5
myChar1 = Mid(testString, 1, 1)
'// test2/4
myChar2 = Mid(testString, 2, 1)
If testString Like myChar1 & "[A-Z]" & myChar1 & "[A-Z]" & myChar1 Then
MsgBox "Matches 1, 3 and 5"
ElseIf testString Like "[A-Z]" & myChar2 & "[A-Z]" & myChar 2 & "[A-Z]" Then
Msgbox "Matches 2 and 4"
End If
或使用Mid()
功能:
If Mid(testString, 1, 1) = Mid(testString, 3, 1) And _
Mid(testString, 3, 1) = Mid(testString, 5, 1) And _
Mid(testString, 1, 1) = Mid(testString, 5, 1) Then
MsgBox "Matches 1, 3 and 5"
ElseIf Mid(testString, 2, 1) = Mid(testString, 4, 1) Then
MsgBox "Matches 2 and 4"
End If
或检查两种情况:
Dim match1 As String, match2 As String
Const testString As String = "ABABA"
match1 = Left(testString, 1) & "[A-Z]" & Left(testString, 1) & "[A-Z]" & Left(testString, 1)
match2 = "[A-Z]" & Left(testString, 1) & "[A-Z]" & Left(testString, 1) & "[A-Z]"
If testString Like match1 Or testString Like match2 Then
MsgBox "findwindow likes it when anything matches"
End If
答案 2 :(得分:1)
答案 3 :(得分:1)
轮到我了:
Function findPattern(inputStr As String) As Variant()
Dim arr() As String
Dim i As Integer
arr = Split(inputStr)
ReDim arr2(UBound(arr)) As Variant
For i = LBound(arr) To UBound(arr)
If Left(arr(i), 1) = Mid(arr(i), 3, 1) And _
Left(arr(i), 1) = Mid(arr(i), 5, 1) And _
Mid(arr(i), 2, 1) = Mid(arr(i), 4, 1) Then
arr2(i) = "True"
Else
arr2(i) = "False"
End If
findPattern = arr2
Next
End Function
Sub trying()
Dim t As String
t = "ABABA BCBCB IOITU"
arr = findPattern(t) 'returns an array {True,True,False}
For x = 0 To 2
Debug.Print arr(x)
Next
End Sub
这假设每个字符串中有多个单词。它返回一个true false的数组。
修改
要找到它,有任何模式使用此UDF:
Function findPattern(inputStr As String) As String
Dim i As Integer
For i = 5 To 1 Step -1
If Asc(Mid(inputStr, i, 1)) > 5 Then
inputStr = Replace(inputStr, Mid(inputStr, i, 1), i)
End If
findPattern = inputStr
Next
End Function
它将返回12121" ABABA"
您可以将其粘贴到工作簿中的模块中,然后像公式一样使用它:=findPattern("A1")
将其复制下来。然后对列进行排序,它将所有类似模式与最模式化(11111)放在一起(12345)。
然后你也可以在这个专栏中筛选你想要的任何模式。
答案 4 :(得分:0)