编写一个单词宏来组织聊天记录

时间:2013-09-09 05:50:03

标签: regex vba replace ms-word word-vba

我需要一些帮助来编写单词宏来组织一些聊天记录。我想要的是消除重复连续出现的名称,无论时间戳如何。除此之外,每个人都将使用自己的格式样式(字体,字体颜色等)。 编辑:原始日志没有格式(即特定字体,字体颜色等)。我希望宏自动为每个用户添加一个特定的(已经存在的)单词样式。

所以,我所拥有的是:

[12:40] Steve: this is an example text.
[12:41] Steve: this is another example text.
[12:41] Steve: this is yet another example text.
[12:45] Bob: some more text.
[12:46] Bob: even more text.
[12:47] Steve: yadda yadda yadda.

预期输出为:

[12:40] Steve: *style1*this is an example text.
this is another example text.
this is yet another example text.*/style1*
[12:45] Bob: *style2*some more text.
even more text.*/style2*
[12:47] Steve: *style1*yadda yadda yadda.*style1*

截至目前,遗憾的是,我对VBA for Applications几乎一无所知。我正在考虑用正则表达式模式搜索名称并将它们分配给变量,将每个匹配与前一个匹配,如果它们相等,则删除后者。问题是我不能说流利的VBA,所以我不知道怎么做我想要的。

到目前为止,我所拥有的只是:

Sub Organize()

    Dim re As RegExp
    Dim names As MatchCollection, name As Match
    re.Pattern = "\[[0-9]{2}:[0-9]{2}\] [a-zA-Z]{1,20}:"
    re.IgnoreCase = True
    re.Global = True
    Set names = re.Execute(ActiveDocument.Range)

    For Each name In names
    'This is where I get lost
    Next name   
End Sub

所以,为了解决这个问题并且我学习了一些VBA,我可以得到一些帮助吗?

编辑:问题已被编辑,以更好地反映我希望宏做的事情。

1 个答案:

答案 0 :(得分:0)

假设您的日志中的每一行都是一个单独的段落,我会在没有Regex的情况下使用.Find object功能。以下代码用于查找您提供的示例数据。

Sub qTest()
    Dim PAR As Paragraph
    Dim PrevName As String

    For Each PAR In ActiveDocument.Content.Paragraphs
        PAR.Range.Select    'highlight current paragraph
            'find name in paragraph
            With Selection.Find
                .ClearFormatting
                .Text = "\]*\:"
                .Execute
            End With
            If Selection.Text = PrevName Then
                'extend region for the whole paragraph
                'end delete it
                ActiveDocument.Range(PAR.Range.Start, Selection.End + 1).Delete
            Else
                PrevName = Selection.Text
                Debug.Print PrevName
            End If

    Next
End Sub