合并正则expression式并填充最less的单元格

Excel中有一个单元格,它在单元格A1中包含一个长string:

"ABC12+BED58,YZ001" 

我有以下正则expression式来匹配我的string中的一些特定的variables

 strPattern = "[AZ]{1,3}[0-9]{2,4}" 

基本上,我需要写一个macros或函数(我更喜欢一个函数实际),将填补细胞A2,A3,A4这样的:

 ABC12 BED58 YZ001 

事情是,string中的参数数量是不确定的(例如,它可以一直穿过A200)。

我想到一个函数get_n_variables(str, n)将返回第N个唯一匹配

这是我迄今为止的进展,但函数返回#VALUE!

 Function simpleCellRegex(Myrange As Range) As String Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim matches As Object strPattern = "[AZ]{1,3}[0-9]{2,4}" If strPattern <> "" Then strInput = Myrange.Value strReplace = "" With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.Test(strInput) Then Set matches = regEx.Execute(strInput) simpleCellRegex = matches(0).SubMatches(0) Else simpleCellRegex = "Not matched" End If End If End Function 

来自MrExcel论坛 :

你不能在一个单元格中放置一个函数来改变其他单元格。 函数不能这样工作。

因此,它应该是一个sub ,就像这样,例如(用inputstring输出所选单元格下的匹配项):

 Sub simpleCellRegex() Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim matches As MatchCollection Dim i As Long, cnt As Long strPattern = "[AZ]{1,3}[0-9]{2,4}" cnt = 1 If strPattern <> "" Then strInput = ActiveCell.Value strReplace = "" With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then Set objMatches = regEx.Execute(strInput) For i = 0 To objMatches.Count - 1 ActiveCell.Offset(cnt).Value = objMatches.Item(i) cnt = cnt + 1 Next End If End If End Sub 

输出:

在这里输入图像说明

如果你使用一个数组,你实际上仍然可以使用一个函数

  • selectB1:D1
  • input这个公式=simpleCellRegex(A1)并按下CTRL + SHIFT + ENTER

如果你不知道有多less比赛进入更多的细胞比可能会比赛

 Function simpleCellRegex(StrIn As String) As Variant Dim regEx As Object Dim regMC As Object Dim X Dim strPattern As String Dim lngCnt As Long strPattern = "[AZ]{1,3}[0-9]{2,4}" Set regEx = CreateObject("vbscript.regexp") With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern If .Test(StrIn) Then Set regMC = .Execute(StrIn) ReDim X(0 To regMC.Count - 1) As String For lngCnt = 0 To UBound(X) X(lngCnt) = regMC(lngCnt) Next simpleCellRegex = X Else simpleCellRegex = "Not matched" End If End With End Function