I want to get some data from Excel table using SQL-query inside macros.
My code is:
Sub Button1_Click()
Dim cn As Object, rs As Object, output As String, sql As String
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Value1 = Range("B4").Value ' = 30.10.2020
Value2 = Range("C4").Value ' = 2
'I want to insert Value2 = 2 inside my SQL query
sql = "SELECT * FROM [Page 1$] WHERE Job = Value2 AND DateTime = Value1"
Set rs = cn.Execute(sql) 'but it doesn't work, stops here
Do
output = output & rs("Name") & ";" & rs(1) & ";" & rs(2) & vbNewLine
Debug.Print rs(0); ";" & rs(1) & ";" & rs(2)
rs.Movenext
Loop Until rs.EOF
MsgBox output
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub
If I try using sql = "SELECT * FROM [Page 1$] WHERE Job = 2", I have no errors.
How could I paste Value2 and Value1 values inside my SQL-query?
sql = "SELECT * FROM [Page 1$] WHERE Job = Value2"to:sql = "SELECT * FROM [Page 1$] WHERE Job = " & Value2sql = "SELECT * FROM [Page 1$] WHERE Job = " & Value1 & Value2