你好,谢谢你。
我正在使用VBA从Excelfile创建非常复杂的Word文档。应有可能激活某些内容,并将写入单元格中的文本转移到word文档中。我已经完成了。但是,如果未激活,则应删除标签“ <>”,不留任何内容。这意味着它不仅应删除文本,还应删除完整的“行”。由于line可能是一个部分,因此我不确定在这里line是否正确。
现在,我使用以下命令找到并替换为“”:
With WordDoc.Content.Find
.Execute FindText:=ReplacementTextF, ReplaceWith:="", Replace:=2
End With
但是我该如何删除行/节?
EDIT1:
示例:
由于替换是可选的,因此用户可以选择文档中所需的文本。因此,也许不需要ReplacementText4。因此,我需要删除“ << ReplacementText4 >>”并删除项目符号。这就是删除行/节的意思。
答案 0 :(得分:2)
这似乎是有关“查找/替换”的问题,但更正确的是有关“查找”的问题,然后在找到的文本的位置进行操作。当查找/替换的选项未涵盖替换条件时,这是常见的要求。需求通过以下模式解决。
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,因为我从他过去介绍过的许多查找/替换示例中得出了这种模式。