在包装的文本值单元格中使用正则表达式

时间:2015-02-18 16:42:55

标签: regex vba excel-vba excel

我有一个这样的单元格:

1 parent
 1 child

我在vba中获得了价值:

Dim nbChild As String
Dim nbParent As String
Sheets("Feuil1").Cells(C.Row - 1, C.Column).Value

但是,我想将父和子的数量放在2个分离变量nbParent和nbChild中,所以我想用正则表达式来捕获组(父级之前的数字和子级之前的数字)。

但我不知道该怎么做。在此先感谢您的帮助

3 个答案:

答案 0 :(得分:1)

Dim arr, parent, child

arr = Split(ActiveCell.Value, Chr(10))'split on hard return
parent=arr(0)
child=arr(1)

'then split each line on space....
debug.print Split(parent," ")(0) 'number
debug.print Split(parent," ")(1) 'text

debug.print Split(child," ")(0) 'number
debug.print Split(child," ")(1) 'text

答案 1 :(得分:0)

使用以下数据:

enter image description here

单击一个单元格并运行:

Sub Family()
    ary = Split(ActiveCell.Value, " ")
    nParent = CLng(ary(0))
    nChild = CLng(ary(2))
    MsgBox nParent & vbCrLf & nChild
End Sub

(不需要正则表达式)

答案 2 :(得分:0)

我同意@ Gary的学生,你似乎不需要正则表达式,但如果你坚持,我认为下面的代码有效。您需要在工具 - >中添加对Microsoft VBScript Regular Expressions 5.5的引用。引用。

 Sub main()
        Dim value As String
        Dim re As VBScript_RegExp_55.RegExp
        Dim matches As VBScript_RegExp_55.MatchCollection
        Dim match As VBScript_RegExp_55.match

        value = Range("A1").value

        Set re = New VBScript_RegExp_55.RegExp
        re.Pattern = "\d+"
        re.Global = True

        Set matches = re.Execute(value)

        For Each match In matches
            Debug.Print match.value
        Next

    End Sub