使用VBA创建后,在Word中删除文本和表

时间:2012-07-26 09:17:26

标签: vba ms-word word-vba mailmerge

我在编写邮件合并时遇到了一些问题,因为我的代码创建的每个内容都必须被删除,以免在合并过程中出现下一个字母。

所以我写了一个测试宏只是为了创建一些表并删除它们。

这是我的进步 - 可以使用名为“test”的书签在新的空Word文件中运行

Sub TabsNText()

    Const k As Integer = 2

    Dim doc As Document
    Dim rng As Range
    Dim tab_rngs(k) As Range
    Dim txt_rngs(k) As Range
    Dim tbl As Table

    Set doc = Word.ActiveDocument
    Set rng = doc.Bookmarks("test").Range

    Dim i As Integer

    For i = 1 To k
        Set txt_rngs(i) = rng
        rng.Text = "Title " & i

        rng.Collapse Direction:=wdCollapseEnd
        rng.InsertParagraphAfter
        rng.Collapse Direction:=wdCollapseEnd

        Set tab_rngs(i) = rng

        Set tbl = doc.Tables.Add(rng, 3, 3)
        tbl.Cell(1, 1).Range.Text = "Table" & i
        tbl.Borders.Enable = True

        Set rng = tbl.Range

        rng.Collapse Direction:=wdCollapseEnd
        rng.InsertParagraphAfter
        rng.Collapse Direction:=wdCollapseEnd
    Next i

    rng.Select

    MsgBox ("Now, let's delete that!")

    For i = 1 To k
        txt_rngs(i).Text=""
        tab_rngs(i).Tables(1).Delete
        doc.Bookmarks.Add Name:="test", Range:=rng
    Next i

End Sub
你知道吗表格将被正确删除。但是文本和段落是什么? 是否有一种方法可以从起点到某个终点进行选择并删除其所有内容。

1 个答案:

答案 0 :(得分:0)

好的 - 我找到了一个简单的解决方案,可以定义从其他范围的起点到终点的范围。 但由于Ranges的位置非常不稳定(特别是在混合文本和表格时),可以使用辅助书签来定义起点。

Sub TabsNText()

    Const k As Integer = 2

    Dim doc As Document
    Dim rng As Range
    Dim tbl As Table
    Const startbkm As String = "test_start"
    Const insertbkm As String = "test"

    Set doc = Word.ActiveDocument
    Set rng = doc.Bookmarks(insertbkm).Range

    doc.Bookmarks.Add Name:=startbkm, Range:=rng

    Dim i As Integer

    For i = 1 To k
        rng.Text = "Title " & i

        rng.Collapse Direction:=wdCollapseEnd
        rng.InsertParagraphAfter
        rng.Collapse Direction:=wdCollapseEnd

        Set tbl = doc.Tables.Add(rng, 3, 3)
        tbl.Cell(1, 1).Range.Text = "Table" & i
        tbl.Borders.Enable = True

        Set rng = tbl.Range

        rng.Collapse Direction:=wdCollapseEnd
        rng.InsertParagraphAfter
        rng.Collapse Direction:=wdCollapseEnd
    Next i

    MsgBox ("Now, let's delete that!")

    doc.Range(doc.Bookmarks(startbkm).Range.start, _
              rng.End).Delete

    doc.Bookmarks.Add Name:=insertbkm, Range:=rng
    doc.Bookmarks(startbkm).Delete


End Sub