使用“For Each”将对象输出到excel Range

时间:2016-07-05 16:33:06

标签: excel vba

我有这段代码使用常规函数:

Set Matches = oReg.Execute(tack)
For Each oMatch In Matches
    Worksheets("Sheet1").Cells(i, t) = oMatch.Value
    t = t + 1       
Next

我在工作表中的不同单元格中打印oMatch.Value时遇到问题,它们都打印在同一个单元格中

如何更改它以将值写入不同的单元格?

1 个答案:

答案 0 :(得分:0)

此代码将两个匹配项中的每一个放在单独的单元格中

Sub test()

    Dim RE As VBScript_RegExp_55.RegExp, REMatches As VBScript_RegExp_55.MatchCollection
    Dim REMatch As VBScript_RegExp_55.Match
    Dim strData As String
    Dim i As Long, t As Long

    strData = "[step 1] title for substeps;  [substep a] step a; [substep b] step b; [substep c] step c;"
    i = 1: t = 1

    Set RE = New VBScript_RegExp_55.RegExp
    With RE
        .MultiLine = False
        .Global = True
        .IgnoreCase = True
        .Pattern = "\[substep [a-zA-Z]\](.*?); {1}"
    End With

    Set REMatches = RE.Execute(strData)

    For Each REMatch In REMatches
        Sheet1.Cells(i, t) = REMatch.Value
        t = t + 1
    Next REMatch

End Sub

在你的循环之前,放Debug.Print Matches.Count以确保有多个匹配。此外,如果您未将Global设置为True,则只能获得一个匹配。