我有 2 个标题或标记是我的 RTF 文档的一部分。 在我的示例中,我显示一个句子,而实际上它将是多个句子或段落。 我使用了括号而不是小于和大于符号,因为它们在我的问题中消失了。 我想做的只是用下面的句子"文本转到这里"替换 2 个标记之间的文本,不带引号。
[嵌入式报告]大量文本,数千个字符,多个段落[/嵌入式报告]
我想将 2 个标记之间的所有文本替换为"文本转到此处"。
它最终会看起来像这样...
"[EmbeddedReport]text goes here[/EmbeddedReport]"
我真的花了 2 天时间试图解决这个问题。 任何帮助将不胜感激。
这是我尝试的最后一件事...
Sub RemoveReport()
Dim c As Range
Dim StartWord As String, EndWord As String
Selection.HomeKey Unit:=wdStory
StartWord = "<ImageTable>"
EndWord = "</ImageTable>"
Set c = ActiveDocument.Content
c.Find.ClearFormatting
c.Find.Replacement.ClearFormatting
With c.Find
.Text = StartWord & "*" & EndWord
' MsgBox (.Text)
.Replacement.Text = "<ImageTable>text goes here</ImageTable>"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
c.Find.Execute
While c.Find.Found
Debug.Print c.Text
'~~> I am assuming that the start word and the end word will only
'~~> be in the start and end respectively and not in the middle
Debug.Print Replace(Replace(c.Text, StartWord, ""), EndWord, "")
c.Find.Execute
Wend
End Sub
Word VBA不是我的专业领域,但它似乎与我几天前回答的问题相似。
事实证明,通配符匹配并没有做我希望它能做的事情,或者至少它不可靠。另外,我在使用尖括号时遇到了一些麻烦,因此这使用了方括号。 我怀疑单词将尖括号视为标记/语法,因此不会将它们解释为 Find 对象中的文本。 可能有一种方法可以解决这个问题,但Word VBA不是我的专长。 可能还有一个更优雅的解决方案,但同样,Word VBA 不是我的专长:)
尝试这样的事情:
Option Explicit
Sub Test()
Dim doc As Document
Dim txtRange As Range
Dim startTag As String
Dim endTag As String
Dim s As Long
Dim e As Long
startTag = "[EmbeddedReport]"
endTag = "[/EmbeddedReport]"
Set doc = ActiveDocument
Set txtRange = doc.Content
'Find the opening tag
With txtRange.Find
.Text = startTag
.Forward = True
.Execute
If .Found Then
s = txtRange.Start
Else
GoTo EarlyExit
End If
End With
'Find the closing tag
Set txtRange = doc.Range(txtRange.End, doc.Content.End)
With txtRange.Find
.Text = endTag
.Forward = True
.Execute
If .Found Then
e = txtRange.End
Else
GoTo EarlyExit
End If
End With
Set txtRange = doc.Range(s, e)
txtRange.Text = startTag & "text goes here" & endTag
Exit Sub
EarlyExit:
MsgBox "Header not found in this document!", vbInformation
End Sub
一开始需要一些时间来弄清楚,但学习浏览 VBA 的对象模型参考文档将使这些任务在将来更容易弄清楚。