访问表到特定Excel电子表格

时间:2015-02-20 15:32:06

标签: vba excel-vba ms-access-2010 excel

我在使用Excel vba将记录从Access表复制到Excel工作表时遇到问题。

docmd打开表后我迷失了 !!!!!!

有人可以帮助Pleassssssseeeeee吗?

由于

这是我的代码:

Sub OpenAccessDB()
    Dim DBFullPath As String
    Dim DBFullName As String
    Dim TableName As String
    Dim TargetRange As Range
    Dim appAccess As Object
    Dim RS As New ADODB.Recordset

    'File Paths and Names*********************************
    DBFullPath = "e:\ccampbellStuff\"
    DBFullName = "2015_02.accdb"
    TableName = "Record Opt Outs"

    'Initiating the Access DB Engine**********************
    Set appAccess = CreateObject("Access.Application")

    'Opening the database
    appAccess.OpenCurrentDatabase (DBFullPath & DBFullName)
    appAccess.Visible = True

    'Open Access Table Called Record Opt Outs****
    **appAccess.DoCmd.Opentable (TableName)**
    'Set RS = appAccess.DoCmd.Opentable (TableName) this didnt work either
    'Set appAccess = Nothing
    'Copy Access Records and Patse to Excel''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Close database
    appAccess.Quit
End Sub

1 个答案:

答案 0 :(得分:2)

我不打算自动化Access本身 - 只需使用ADO:

Sub loadAccessData()
'////////////////////////////////////////////////////////////////////
' requires a reference to a Microsoft ActiveX Data Objects Library.
'////////////////////////////////////////////////////////////////////
   Dim cn               As ADODB.Connection
   Dim sQuery           As String
   Dim rs               As ADODB.Recordset
   Dim sDB_Path         As String
   Dim ws               As Worksheet

'    output to activesheet
   Set ws = ActiveSheet

'    Path to database
   sDB_Path = "c:\somepath\database1.accdb"

   Set cn = New ADODB.Connection
'    open connection to database
   With cn
      .CursorLocation = adUseServer
      .Provider = "Microsoft.ACE.OLEDB.12.0"
      .ConnectionString = "Data Source=" & sDB_Path & ";"
      .Open
   End With

'    SQL query string - change to suit
   sQuery = "SELECT * FROM tblTest"

'    Create New Recordset
      Set rs = New ADODB.Recordset

      ' open recordset using query string and connection
      With rs
         .Open sQuery, cn, adOpenStatic, adLockPessimistic, adCmdText
         ' check for records returned
         If Not .EOF Then
            'Populate field names
            For i = 1 To .Fields.Count
               ws.Cells(1, i) = .Fields(i - 1).Name
            Next i
            ' Load data starting at A2
            ws.Cells(2, 1).CopyFromRecordset rs
         End If
         .Close
      End With

      ' clean up
      cn.Close
End Sub