一旦看到要创建部件、执行读取过程中有新窗口打开关闭,那这个方法就操作各种隐患,绝对不是最优解。
1.读取office文件及各种图片、文档
Set doc = Application.ActiveDocument
doc.Tables(1).Cell(3, 2).Range.InsertFile "C:\1.doc", "", False, False, False
这里是在word文档中插入的表格插入了内容,在表格里同样适用
doc.Tables(1).Cell(3, 2).Range就是单元格对象
2.保存内容
这也是非常简单
Application.Quit
看似关闭,实则因为更改了文本,他会询问是否保存
但如果只想保存word文档中的部分插入的表格呢?
如图,画叉的是不要的
首先,我们新建文档
Set wordApp = New Word.Application
With wordApp
.Visible = True
.Documents.Add
End With
再新建表格
Set Tbl = .ActiveDocument.Tables.Add(.ActiveDocument.Range(0, 0), numrows:=3, numcolumns:=2) '在文档开头插入一个3行2列的表格
With Tbl.Borders '设置表格边框线为单实线
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleSingle
End With
再同步内容
Set wordApp = New Word.Application
With wordApp
.Visible = True
.Documents.Add
Set Tbl = .ActiveDocument.Tables.Add(.ActiveDocument.Range(0, 0), numrows:=3, numcolumns:=2)
.ActiveDocument.Tables(1).Cell(1, 1).Range = Application.ActiveDocument.Tables(1).Cell(1, 1).Range
.ActiveDocument.Tables(1).Cell(2, 1).Range = Application.ActiveDocument.Tables(1).Cell(2, 1).Range
.ActiveDocument.Tables(1).Cell(3, 1).Range = Application.ActiveDocument.Tables(1).Cell(3, 1).Range
.ActiveDocument.Tables(1).Cell(1, 2).Range = Application.ActiveDocument.Tables(1).Cell(1, 2).Range
.ActiveDocument.Tables(1).Cell(2, 2).Range = Application.ActiveDocument.Tables(1).Cell(2, 2).Range
End With
最后,就是保存了
With wordApp
.Quit
End With
以下是完整代码
Private Sub CommandButton2_Click()
Set wordApp = New Word.Application
With wordApp
.Visible = True
.Documents.Add
Set Tbl = .ActiveDocument.Tables.Add(.ActiveDocument.Range(0, 0), numrows:=3, numcolumns:=2)
With Tbl.Borders '设置表格边框线为单实线
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleSingle
End With
.ActiveDocument.Tables(1).Cell(1, 1).Range = Application.ActiveDocument.Tables(1).Cell(1, 1).Range
.ActiveDocument.Tables(1).Cell(2, 1).Range = Application.ActiveDocument.Tables(1).Cell(2, 1).Range
.ActiveDocument.Tables(1).Cell(3, 1).Range = Application.ActiveDocument.Tables(1).Cell(3, 1).Range
.ActiveDocument.Tables(1).Cell(1, 2).Range = Application.ActiveDocument.Tables(1).Cell(1, 2).Range
.ActiveDocument.Tables(1).Cell(2, 2).Range = Application.ActiveDocument.Tables(1).Cell(2, 2).Range
.ActiveDocument.Tables(1).Cell(3, 2).Range.InsertFile myapppath, "", False, False, False'!!!!!这里的myapppath是上面插入的文件的路径!!!!!
.Quit
End With
Set wordApp = Nothing
Application.StatusBar = False
End Sub