excel - 如何使用excel-vba创建word文档删除部分

标签 excel vba ms-word format

您好,提前谢谢您。

我正在使用 VBA 从 Excel 文件创建一个非常复杂的 Word 文档。应可以激活某些内容,并且单元格中写入的文本应传输到 Word 文档。我已经做好了。但如果它没有被激活,标签“<>”将被删除,不留下任何东西。这意味着它不仅要删除文本,还要删除完整的“行”。由于 line 可能是一个部分,我不确定 just line 在这里是否是正确的词。

现在我找到它们并将其替换为“”,使用:

With WordDoc.Content.Find
   .Execute FindText:=ReplacementTextF, ReplaceWith:="", Replace:=2
End With

但是我怎样才能删除该行/部分呢?

编辑1:

示例:

enter image description here

由于替换是可选的,用户可以在文档中选择他想要的文本。因此,也许不需要 ReplacementText4。所以我需要删除“<< ReplacementText4 >>”并删除项目符号。这就是我所说的删除行/节的意思。

最佳答案

这似乎是一个有关“查找/替换”的问题,但更正确的是一个有关“查找”的问题,然后在找到的文本位置执行某些操作。当查找/替换的选项未涵盖替换条件时,这是一个常见的要求。该要求通过以下模式解决。

    With <Range>
        With .Find
            <setup find criteria for find>
            .wrap = wdFindStop ' This is essential
        End with
        Do while .Find.Found
            <do your actions here>
            <use .duplicate if you want to do something with the found range
            <e.g. to delete the paragraph with the found text
            .duplicate.paragraphs(1).range.delete
            <move the found range to after the end of the found range>
            .collapse direction:=wdcollapseend
            .moveend unit:=wdCharacter, count:=1
            .find.execute ' must include this to find next instance

        loop

    End with <range>

将此模式转换为代码给出

Sub DeleteParasWithText(this_doc As Word.Document, this_find_text As String)

    With this_doc.content
            With .Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .text = this_find_text
                .Wrap = wdFindStop
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchByte = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute

            End With

            Do While .Find.Found
                ' In the OP case we just want to delete the paragraph
                ' containing the found text
                .Duplicate.Paragraphs(1).Range.Delete
                .Collapse Direction:=wdCollapseEnd
                .Move unit:=wdCharacter, Count:=1
                .Find.Execute
            Loop

        End With
End Sub

在介绍这一点时,我还要感谢@Macropod,因为我从他过去介绍的许多查找/替换示例中得出了这种模式。

关于excel - 如何使用excel-vba创建word文档删除部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317548/

相关文章:

Excel宏突出显示与当前单元格中的值匹配的所有单元格

sql-server - 从远程服务器文件系统上的 .xlsx 或 .csv 文件获取数据的 OPENROWSET 或 OPENDATASOURCE 示例

excel - VBA中宏的可变错误

excel - 使用嵌套循环对特定单元格求和

php - 在 PHP 中读取 docx(Office Open XML)

vba - 如何使用空白单元格作为引用来执行 sumif?

vba - EXCEL VBA : How to convert dd/mm/yy into yyyy. mm.dd

mysql - 按顺序插入或打开表单到特定记录,同时仍然可以查看其他记录

ms-word - Wordconv 不起作用

vba - 从 Powershell 中调用 Microsoft Word VBA 代码