我是新來的Excel VBA中的正則表達式,一直在看關於堆棧溢出關於它的幾個問題,發現通過以下鏈接"How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops"正則表達式匹配年?
一個偉大的有一些非常有用的代碼在這裏,我想我可能嘗試學習和適應我的目的,我試圖匹配一個4位數的字符串,代表電子表格中一個單元格的年份。 「2016是一個好年份」將產生「」。
我用了一些稍微改變的代碼從那個問題發佈在那裏,它設法識別一個字符串包含一年,但我不知道如何分離和提取字符串從其餘的單元格內容,即。在相鄰的單元格上自己獲取,我應該做出什麼改變?
Private Sub splitUpRegexPattern()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("D2:D244")
For Each c In Myrange
strPattern = "([0-9]{4})" 'looks for (4 consecutive numbers)
If strPattern <> "" Then
strInput = c.Value
strReplace = "$1"
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
c.Offset(0, 5) = regEx.Replace(strInput, "$1") 'puts the string in an adjacent cell
Else
c.Offset(0, 5) = "(Not matched)"
End If
End If
Next
End Sub
的'regEx.Execute()'函數返回匹配對象將包含'在多個子匹配的,每個捕獲組'(圖案)你的模式。你會發現很多這樣的描述,例如在SO上。另外,將模式分配移出循環,它是不變的。最後,爲了匹配一年你會使用'([12] [0-9] {3})'來匹配只有最後一個和當前的千年。 – user1016274
謝謝,得到它正在使用regEx.Execute() – user3545370