1

然后我使用创建对象打开了 MS 单词,我必须搜索一个单词并将其替换为一个表。我能够使用 VBA 构建一个表。但是,我需要用表格替换那个词(匹配),然后根据单元格填充表格。这是我的代码:-

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 
4

1 回答 1

0

如果您进行更多面向对象的编程,而不是依赖“ActiveDocument”等,这将有所帮助。

首先定义一个Range代表Document.Content. 该Find.Execute方法,如果返回True,将把这个Range对象重新定义为找到的单词。因此,您可以将其用作方法中的Range参数Tables.Add

从评论更新我意识到您正在实例化 Word,然后添加一个新的(空白)文档。正如预期的那样,Find.Execute不会在此文档中找到任何内容。相反,我修改为专门从已知文件路径打开文档。

'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
于 2013-10-18T01:18:09.460 回答