使用 SQL 将 MS Access 信息返回到 Excel 电子表格

问题描述

我希望在 VBA 上运行 sql 查询,该查询将从 MS Access 返回信息到单元格 A1。

目前,我正在运行 sql 查询 SELECT AccountNumber,BorrowerName from AccountTable;,它只返回 A 列中的帐号 - 它不返回 BorrowerName。同样,如果我要运行 SELECT * from AccountTable; ,它将只返回 AccountNumber 列。有什么想法吗?

(忽略直到Dim conn As New Connection

'runs an sql query
Sub RunQueryOnAccess()

    'Declaring year value of 1 month & 2 month
    'This is important to compare datasets from 2 months ago & last month
    Year_1M = Format(Date - 27,"YYYY")

    'Declaring month value of 1 month & 2 month
    'This is important to compare datasets from 2 months ago & last month
    Month_1M = Format(Date - 27,"MM")

    'This translates the current month from number to character format
    MonthChar_1 = MonthName(Month_1M,False)

    'opens the workbook before
    'specifiying the file locations
    pStr = "Z:\Danny Tool Test Folder\Monthly Files" & "\" & Year_1M & "\" & _
    Month_1M & ". " & MonthChar_1 & " " & Year_1M & "\"

    otherFile = "Monthly Reporting Tool"
    
    'checking to see that the reporting tool is open,declaring it as MonthlyRepTool
    For Each wb In Application.Workbooks
        If wb.Name Like otherFile & "*" Then
           Set MonthlyRepTool = Workbooks(wb.Name)
        End If
    Next wb
    
    Dim RepDash As String
    
    RepDash = "Reporting Dashboard"

    Dim conn As New Connection,rec As New Recordset
    Dim DBPATH,PRVD,connString,query As String
    'Declaring fully qualified name of database. Change it with your database's location and name.
    DBPATH = "Z:\Danny Tool Test Folder\Database\MasterFile_February2021.accdb"
    'This is the connection provider. Remember this for your interview.
    PRVD = "Microsoft.ace.OLEDB.12.0;"
    'This is the connection string that you will require when opening the the connection.
    connString = "Provider=" & PRVD & "Data Source=" & DBPATH
    'opening the connection
    conn.Open connString
    'the query I want to run on the database.
    query = "SELECT AccountNumber,BorrowerName from AccountTable;"

    
    'running the query on the open connection. It will get all the data in the rec object.
    rec.Open query,conn
    'clearing the content of the cells
    Cells.ClearContents
    'getting data from the recordset if any and printing it in column A of excel sheet.
    If (rec.RecordCount <> 0) Then
        do while Not rec.EOF
            Range("A" & Cells(Rows.count,1).End(xlUp).Row).Offset(1,0).Value2 = _
            rec.Fields(0).value
            rec.MoveNext
        Loop
    End If
    
    'closing the connections
    rec.Close
    conn.Close


End Sub

解决方法

使用这个:

Range("A2").CopyFromRecorset rec

这会将整个记录集复制到您的工作表中,快速,无循环。