office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

access导出数据表内容到word文档中

2020-12-23 08:00:00
tmtony8
原创
119

access是office的组件,既然是同一个母亲,那么和Excel,word之间的交互显然是非常方便的。

我们有时要把access的数据导出到Excel表格,也会把access数据导出到word中。

如下,把access中人员信息表的人员信息导入到word中,并生成表格:


On Error GoTo Err_Add
    Dim WdApp As Word.Application
    Dim WdDoc As Word.Document
    Dim StrAdr As String
    Dim Db As DAO.Database
    Dim rs As DAO.Recordset
    Set Db = CurrentDb
    Set rs = Db.OpenRecordset("员工信息")    
    StrAdr = CurrentProject.Path & "\示例1.docx"
    Set WdApp = GetObject(, "Word.Application")
    Set WdDoc = WdApp.Documents.Open(StrAdr)
    WdApp.Visible = True
    '在word中创建一个两列的表格,并添加边框
    WdDoc.Tables.Add Selection.Range, 1, 2
    For Each atable In WdDoc.Tables
        atable.Borders.OutsideLineStyle = wdLineStyleSingle
        atable.Borders.InsideLineStyle = wdLineStyleSingle
    Next atable
    '将Access数据表中的数据添加到创建的word表格中
    Set Db = CurrentDb
    Set rs = Db.OpenRecordset("员工信息")
    With WdApp.Selection
            .TypeText "姓名"    '添加表头
            .MoveRight wdCell    '向右移动
            .TypeText "性别"
            .MoveRight wdCell
            Do While rs.EOF = False
                .TypeText rs![姓名]
                .MoveRight wdCell
                .TypeText rs![性别]
                .MoveRight wdCell
                rs.MoveNext
            Loop
    End With    
    WdApp.Selection.Rows.Delete  '删除最后的空行
 
Err_Add:
    If Err = 429 Then
        Set WdApp = CreateObject("Word.Application")
        Resume Next
    End If
    WdDoc.Save
End Sub


    分享