我想知道是否有可能使用一些VBA在一大堆5char字符串中查找定義的模式?我已經探索了「instr」函數,但我不確定它是否會執行我所需要的任務,基本上可以像下面那樣查找字符串中的模式;Excel VBA字符串評估
ABABA
BCBCB
.....
EFEFE
或者任何這樣的圖案,其中所述第一字符是相同的字符3 & 5,以及第二字符是相同的炭4.
任何幫助或方向將受到歡迎。
親切的問候
吉姆
我想知道是否有可能使用一些VBA在一大堆5char字符串中查找定義的模式?我已經探索了「instr」函數,但我不確定它是否會執行我所需要的任務,基本上可以像下面那樣查找字符串中的模式;Excel VBA字符串評估
ABABA
BCBCB
.....
EFEFE
或者任何這樣的圖案,其中所述第一字符是相同的字符3 & 5,以及第二字符是相同的炭4.
任何幫助或方向將受到歡迎。
親切的問候
吉姆
你可以不用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)
只需更換「亞的斯亞貝巴」與相應的單元格地址,這就是它
試試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
OR檢查兩個條件:
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
輪到我了:
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
這是假設你在每個字符串的多個詞。它返回一個真正的假數組。
編輯
要發現它有任何的模式使用這個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
您可以在工作簿中的模塊中粘貼此則像公式一樣使用它:=findPattern("A1")
將其複製下來。然後在列上排序,它將所有類似圖案與最模式化(11111)一起放到最少(12345)。
然後你也可以在這個列上過濾你想要的任何模式。
請添加一個源文本的例子和你想要的預期結果的例子。 – zedfoxus
模式總是像上面那樣是1,3,5和2,4,或者你只是在尋找任何模式? –
嗨@zedfoxus 道歉,如果問題是模糊的。源文本將是由字母組成的隨機5個字符串的列表。我只需要某種標誌來確定我正在尋找的模式是否存在於每個字符串中。 – jimiclapton