0
如何在ms中執行查詢從Excel VBA代碼或宏中訪問db。 MS-Access查詢接受一些參數,需要從Excel傳遞。 感謝從excel運行訪問查詢並將參數傳遞給查詢
如何在ms中執行查詢從Excel VBA代碼或宏中訪問db。 MS-Access查詢接受一些參數,需要從Excel傳遞。 感謝從excel運行訪問查詢並將參數傳遞給查詢
這是一個可能性:
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
您也可以參考在線的SQL從Excel中的數據集。
編輯再評論
使用命令:
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
這使用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
所以它運行查詢並將其放在你喜歡的地方。 strQuery是數據庫或SQL字符串中查詢的名稱。
何ou,,謝謝你的回覆。我需要執行ms-access查詢並獲得結果。你的示例給出了連接到數據庫和保存數據的輸入。謝謝。 – dps123 2011-02-25 21:16:29
感謝Remou,這有助於.. – dps123 2011-02-25 22:47:50