gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:16:39 26 4
gpt4 key购买 nike

您好,提前谢谢您。

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com