我是新来的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