简体   繁体   中英

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. 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.

Start by defining a Range object that represents the Document.Content . The Find.Execute method, if returns True , will redefine this Range object to the found word. So you can use this as the Range argument in the Tables.Add method.

Update from comments I realize that you are instantiating Word, and then adding a new (blank) document. As expected, the Find.Execute will not find anything in this document. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM