![](/img/trans.png)
[英]Use Excel-VBA to create and Insert String/Text AND Image to Word Document table-cell
[英]How to delete a section using excel-vba to create a word document
你好,提前谢谢你。
我正在使用 VBA 从 Excel 文件中创建一个非常复杂的 Word 文档。 应该可以激活某些东西,并且将在单元格中写入的文本传输到 Word 文档。 我已经完成了。 但是如果它没有被激活,标签“<>”将被删除,不留下任何东西。 这意味着它不仅应删除文本,还应删除完整的“行”。 由于 line 可能是一个部分,我不确定 line 在这里是否正确。
现在我使用以下方法找到并用“”替换它们:
With WordDoc.Content.Find
.Execute FindText:=ReplacementTextF, ReplaceWith:="", Replace:=2
End With
但是我怎样才能删除该行/部分呢?
编辑1:
例子:
由于替换是可选的,用户可以在文档中选择他想要的文本。 因此,也许不需要 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,因为我从他过去提出的许多查找/替换示例中得出了这种模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.