简体   繁体   English

如何使用excel VBA运行访问查询?

[英]How to run access query using excel VBA?

I am fairly new to Access and I have been trying for a while to run an Access query and paste the results in Excel using VBA. 我是Access的新手,我一直尝试运行Access查询并使用VBA将结果粘贴到Excel中。 I have combined some code I found and I think I almost have it but cannot figure out the last step. 我已经结合了一些我找到的代码,我想我几乎已经拥有了它,但无法弄清楚最后一步。 Here is the code: 这是代码:

Sub test()


Dim ws As Worksheet
Dim A As Object
Dim rs As Object

Application.DisplayAlerts = False

Set A = CreateObject("Access.Application")
Set ws = ThisWorkbook.Sheets("Sheet1")

A.Visible = True
A.OpenCurrentDatabase ("access database path")
A.DoCmd.OpenQuery ("query name")

Set rs = A.CurrentDb().QueryDefs("query name").OpenRecordset()

If Not rs.EOF Then
    ws.Range("A1").CopyFromRecordset rs
End If

rs.Close

 Application.DisplayAlerts = True

End Sub

I am trying to run the query and paste the results in cell A1 in sheet 1. 我正在尝试运行查询并将结果粘贴到工作表1中的单元格A1中。

I get a "run time error 3219" for the line: 我得到一行“运行时错误3219”:

Set rs = A.CurrentDb().QueryDefs("query name").OpenRecordset()

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks, 谢谢,

G G

I adapted your code to fetch data from an Access query without needing to create a full Access.Application instance. 我调整了您的代码以从Access查询中获取数据,而无需创建完整的Access.Application实例。 Tested and working in Excel 2010. 在Excel 2010中测试并使用。

Const cstrPath As String = "C:\share\Access\Database2.accdb"
Const cstrQuery As String = "qryBase"
Dim dbe As Object 'DAO.DBEngine '
Dim rs As Object 'DAO.Recordset '
Dim ws As Worksheet

Application.DisplayAlerts = True 'leave alerts on during testing '
Set dbe = CreateObject("DAO.DBEngine.120")
Set rs = dbe.OpenDatabase(cstrPath).OpenRecordset(cstrQuery)

If Not rs.EOF Then
    Set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Range("A1").CopyFromRecordset rs
End If

rs.Close
Application.DisplayAlerts = True

I would use ADODB recordset. 我会使用ADODB记录集。 Try the below code. 请尝试以下代码。 Here I'm connecting to an excel workbook, but you can use the same logic for access database, you just need to change the connection string. 这里我连接到一个excel工作簿,但你可以使用相同的逻辑访问数据库,你只需要更改连接字符串。

Private con As ADODB.Connection
Private ra As ADODB.Recordset



' SqlString = SQL Query
' Sht = Sheet Name, where the output needs to be displayed
' Rng = Range ("C5"), where the output needs to be displayed

Sub DoSql(SqlString As String, Sht As String, Rng As String, Optional IncludeHeading As Boolean = False)

Dim a As String

Dim res As Variant

Set con = New ADODB.Connection
Set ra = New ADODB.Recordset

res = ""

'a = Set the appropriate connection string for your database
'The below connection is referring to the same excel workbook which contains the macro


a = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & ThisWorkbook.FullName & """;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"

'MsgBox a
'MsgBox SqlString

If Not Left("" & con, 8) = "Provider" Then
    con.Open a
End If

If Not ra.State = 0 Then
    ra.Close
End If

ra.Open SqlString, con

If Not (ra.EOF And ra.BOF) Then
    ra.MoveFirst

    Sheets(Sht).Select

    If IncludeHeading = True Then
        For intColIndex = 0 To ra.Fields.Count - 1
            Range(Rng).Offset(0, intColIndex).Value = ra.Fields(intColIndex).Name
        Next
        Range(Rng).Offset(1, 0).CopyFromRecordset ra
    Else
        Range(Rng).CopyFromRecordset ra
    End If

End If
ra.Close
con.Close



End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM