[英]How to replace a word in MS Word to a table by VBA
I have opened the MS word using create object then ,I have to search for a word and replace it with a table.I was able to build a table using VBA. 我已经使用create object打开了MS单词,然后我必须搜索一个单词并将其替换为表格。我能够使用VBA建立一个表格。 But, I need to replace that word (Matched) with a Table and later fill the table as per cell. 但是,我需要用表格替换该单词(匹配),然后按单元格填充表格。 This is my code:- 这是我的代码:
Dim MyApp As New Word.Application
Dim MyDoc As Word.Document
Set MyDoc = MyApp.Documents.Add
MyApp.Visible = True
MyDoc.Activate
With ActiveDocument.Content.Find
.Text = "blue"
.Forward = True
.Execute
If .Found = True Then .Parent.Bold = True
End With
MyApp.ActiveDocument.Tables.Add Range:=MyApp.Selection.Range, numrows:=5, numcolumns:=5
MyApp.ActiveDocument.Save
MyApp.Quit
It will help if you do more object-oriented programming, instead of relying on "ActiveDocument", etc. 如果您进行更多的面向对象的编程,而不是依赖于“ ActiveDocument”等,这将有所帮助。
Start by defining a Range
object that represents the Document.Content
. 首先定义一个表示Document.Content
的Range
对象。 The Find.Execute
method, if returns True
, will redefine this Range
object to the found word. 如果返回True
,则Find.Execute
方法将将此Range
对象重新定义为找到的单词。 So you can use this as the Range
argument in the Tables.Add
method. 因此,可以将其用作Tables.Add
方法中的Range
参数。
Update from comments I realize that you are instantiating Word, and then adding a new (blank) document. 从注释更新我意识到您正在实例化Word,然后添加一个新的(空白)文档。 As expected, the Find.Execute
will not find anything in this document. 与预期的一样, Find.Execute
将在此文档中找不到任何内容。 Instead, I revised to specifically open a document from a known file path. 相反,我修改为从已知文件路径专门打开文档。
'Create a new instance of MS Word
Dim MyApp As New Word.Application
Dim MyDoc As Word.Document
Dim wdRange As Word.Range
'Open an existing Word file:
Set MyDoc = MyApp.Documents.Open("c:\myfile.docx") '# REVISE AS NEEDED
'Make MS Word visible:
MyApp.Visible = True
'Assign the wdRange variable to the document's Content
Set wdRange = MyDoc.Content
'Use the Find method within wdRange:
With wdRange.Find
.Text = "blue"
.Forward = True
.Execute
If .Found = True Then
.Parent.Bold = True
' Since Find.Execute resizes the wdRange to the "found" word, we can
' use this wdRange as the Range argument for Tables.Add:
MyDoc.Tables.Add Range:=wdRange, numrows:=5, numcolumns:=5
End If
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.