使用 VBA 在 Word 中使用 Content.Find 对象搜索文本并恢复找到的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11480421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search text with Content.Find object in Word with VBA and recover the text found
提问by javier
I want to search an entire MSWord document for a text with wildcards and recover the strings found.
我想在整个 MSWord 文档中搜索带有通配符的文本并恢复找到的字符串。
something like that:
类似的东西:
Sub Macro1()
Dim c As Range
Set c = ActiveDocument.Contentsdf
c.Find.ClearFormatting
c.Find.Replacement.ClearFormatting
With c.Find
.Text = "start[abcde]end"
.Replacement.Text = ""
.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.Find.TextFound
c.Find.Execute
Wend
End Sub
but the method c.Find.TextFound
does not exists. Is there any way to recover the text without recurring to Selection.Text
?
但该方法c.Find.TextFound
不存在。有没有办法恢复文本而不重复Selection.Text
?
回答by Siddharth Rout
Try this.
尝试这个。
Sub Sample()
Dim c As Range
Dim StartWord As String, EndWord As String
StartWord = "Start": EndWord = "End"
Set c = ActiveDocument.Content
c.Find.ClearFormatting
c.Find.Replacement.ClearFormatting
With c.Find
.Text = StartWord & "*" & EndWord
.Replacement.Text = ""
.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
回答by user11979710
I've been searching for a way to print a certain number of pages as long as it has a certain word.
我一直在寻找一种方法来打印一定数量的页面,只要它有一个特定的词。
Basically I have 3 files and I have to print them and organize them by shifts. Each of them as the words Shift 1 2 and 3 on them. I managed to put them all printing at once but I want to print Shift 1 from the first file, shift 2 from the second file, and so on till shift 3 of file 5. I just need a macro code that will search the word "shift 1" in the file and print only the pages that contain that word. Then is basically applying the same code to all the files, changing 1 to 2 and to 3.
基本上我有 3 个文件,我必须打印它们并按班次组织它们。它们中的每一个都作为 Shift 1 2 和 3 放在它们上面。我设法将它们一次全部打印出来,但我想从第一个文件打印 Shift 1,从第二个文件打印 Shift 2,依此类推,直到文件 5 的 shift 3。我只需要一个宏代码来搜索单词“ shift 1" 并仅打印包含该单词的页面。然后基本上是将相同的代码应用于所有文件,将 1 更改为 2 和 3。
Correct me if I'm wrong.
如果我错了纠正我。