我有2个标题或标记,它们是我的RTF文档的一部分。在我的例子中,我正在显示一个句子,而实际上它将是多个句子或段落。我使用括号而不是小于和大于符号,因为它们在我的问题中消失了。我想做的就是用以下句子替换2个标记之间的文本,“text goes here”,不带引号。
[EmbeddedReport]大量文字,数千个字符,多个段落[/ EmbeddedReport]
我想要替换“text goes here”替换的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
答案 0 :(得分:2)
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的object model reference文档将使这些任务在将来更容易理解。