vba 从 excel 运行访问查询并将参数传递给查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5122582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:44:29  来源:igfitidea点击:

Run access query from excel and pass paramerts to the query

excelms-accessvbaaccess-vba

提问by dps123

How to execute a query in ms access db from Excel VBA code or macro. MS-Access query accepts some parameters, that needs to be passed from Excel. Thanks

如何从 Excel VBA 代码或宏在 ms access db 中执行查询。MS-Access 查询接受一些需要从 Excel 传递的参数。谢谢

回答by Fionnuala

Here is one possibility:

这是一种可能性:

Dim cn As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String

strFile = "C:\docs\Test.mdb"

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile

''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")

cn.Open strCon

strSQL = "INSERT INTO ATable (AField) " _
& "VALUES (" & Sheet1.[A1] & ")"

cn.Execute strSQL

cn.Close
Set cn = Nothing

You can also refer in-line in the sql to a dataset from Excel.

您还可以在 sql 中内联引用 Excel 中的数据集。

EDIT re comments

编辑重新评论

Using a command:

使用命令:

strSQL = "SELECT * FROM ATable " _
& "WHERE AField = @AField"

With cmd
    Set .ActiveConnection = cn
    .CommandText = strSQL
    .CommandType = 1 'adCmdText

    ''ADO Datatypes are often very particular
    ''adSmallInt = 2 ; adParamInput = 1
    .Parameters.Append .CreateParameter("@AField", 2, 1, , Sheet1.[A1])

End With
Set rs = cmd.Execute 

See also: http://support.microsoft.com/kb/181782

另见:http: //support.microsoft.com/kb/181782

回答by Steve Mallory

This uses ADODB.

这使用 ADODB。

Set m_Connection = New Connection

If Application.Version = "12.0" Then
    m_Connection.Provider = "Microsoft.ACE.OLEDB.12.0"
Else
    m_Connection.Provider = "Microsoft.Jet.OLEDB.4.0"
End If

m_Connection.Open <full path to Access DB>
If m_Connection.State > 0 Then

    Dim rsSource As New Recordset
    rsSource.Open strQuery, m_Connection, adOpenForwardOnly, adLockReadOnly

    Dim result As Long
    Dim rngTarget As Range
    rngTarget = ThisWorkbook.Worksheets(m_SheetName).Range("A1")

    If Not rsSource.BOF Then
        result = rngTarget.CopyFromRecordset(rsSource)
    End If

    If rsSource.State Then rsSource.Close
    Set rsSource = Nothing

End If

So it runs the query and puts it where you like. strQuery is the name of a query in the db or an SQL string.

所以它运行查询并将它放在你喜欢的地方。strQuery 是数据库中查询的名称或 SQL 字符串。