问题
Im new at trying to construct queries out of vba. I am trying to figure out how to pass a variable inside the VBA syntax. Mind showing me where im dumb?
I tried this below but there's an automation error that pops up. Ive noticed from playing aroudn that automation errors come up when youve just got syntax wrong, so hopefully its something small?
Any help is greatly appreciated
Sub GetDataFromAccess()
Dim cmd As New ADODB.Command, rs As ADODB.Recordset
Dim recordNum As Integer
recordNum = 7
cmd.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ashleysaurus\Desktop" & "\" & "xyzmanu3.accdb"
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT * FROM Invoice WHERE OrderNumber <" & "'" & recordNum & "'" & "ORDER BY OrderNumber ASC"
Set rs = cmd.Execute
Sheet1.Range("A2").CopyFromRecordset rs
rs.Close
cmd.ActiveConnection.Close
Debug.Print "Done!"
End Sub
回答1:
Assuming OrderNumber is a number, do not use quotes. Also make sure you have a space before Order By:
cmd.CommandText = "SELECT * FROM Invoice WHERE OrderNumber <" & recordNum & " ORDER BY OrderNumber ASC"
回答2:
While learning to build VBA queries, consider parameterized queries and avoid any need of quotes! This is an industry best practice across all languages when passing values in dynamic SQL queries.
Sub GetDataFromAccess()
Dim cmd As New ADODB.Command, rs As ADODB.Recordset
Dim recordNum As Integer
recordNum = 7
With cmd
.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source=C:\Users\Ashleysaurus\Desktop" & "\" & "xyzmanu3.accdb"
.CommandType = adCmdText
.CommandText = "SELECT * FROM Invoice" _
& " WHERE OrderNumber < ? ORDER BY OrderNumber ASC"
End With
cmd.Parameters.Append cmd.CreateParameter("recordNumParam", adInteger, adParamInput, 10)
cmd.Parameters(0).Value = recordNum
Set rs = cmd.Execute
Sheet1.Range("A2").CopyFromRecordset rs
rs.Close
cmd.ActiveConnection.Close
Debug.Print "Done!"
End Sub
来源:https://stackoverflow.com/questions/38023187/pass-vba-variable-into-access-queryexcel-vba