CodeItBetter Programming Another VB Programming Blog

How to copy data from an Access database into an Excel workbook using a Recordset

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'Database - How to copy data from an Access database into an Excel workbook using a Recordset
'Open the database and build the Recordset containing the data you want to
'transfer. Then open the Excel workbook, find the worksheet that should contain
'the data, create a Range on the worksheet, and use its CopyFromRecordset method
'to load the data. This example also calls AutoFit to make the column widths fit
'the data.

Private Sub cmdLoad_Click()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim excel_app As Excel.Application
    Dim excel_sheet As Excel.Worksheet
 
    Screen.MousePointer = vbHourglass
    DoEvents
 
    ' Open the Access database.
    Set conn = New ADODB.Connection
    conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & _
        txtAccessFile.Text
    conn.Open
 
    ' Select the Access data.
    Set rs = conn.Execute("Books")
 
    ' Create the Excel application.
    Set excel_app = CreateObject("Excel.Application")
 
    ' Uncomment this line to make Excel visible.
    '    excel_app.Visible = True

    ' Open the Excel workbook.
    excel_app.Workbooks.Open txtExcelFile.Text
 
    ' Check for later versions.
    If Val(excel_app.Application.Version) >= 8 Then
        Set excel_sheet = excel_app.ActiveSheet
    Else
        Set excel_sheet = excel_app
    End If
 
    ' Use the Recordset to fill the table.
    excel_sheet.Cells.CopyFromRecordset rs
    excel_sheet.Cells.Columns.AutoFit
 
    ' Save the workbook.
    excel_app.ActiveWorkbook.Save
 
    ' Shut down.
    excel_app.Quit
    rs.Close
    conn.Close
 
ExitHere:
    Screen.MousePointer = vbDefault
End Sub
Filed under: Database Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.