It would be great if someone helps on this.
I would like to provide cell reference from seperate sheet as a parameter in Where query I mean instead of a string "Arunraj S", I need to give reference from the range ("c3") of sheet1("PDA").
It is retrieving fine while giving the direct string through where query.
But It's throwing syntax error when I tried to change the query like below;
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] =" & Sheets("PDA").Range(C3).value
Here is my code :
Sub Pull_Data_from_Excel_with_ADODB()
Dim cnStr As String
Dim rs As ADODB.Recordset
Dim query As String
Dim fileName As String
fileName = "C:\Users\nizamudeen.s\Desktop\PDA Template.xlsx"
cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & fileName & ";" & _
"Extended Properties=Excel 12.0"
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE [Employee Name] = 'Arunraj S';"
Set rs = New ADODB.Recordset
rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified
Cells.Clear
Range("A2").CopyFromRecordset rs
Dim cell As Range, i As Long
With Range("A1").CurrentRegion
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
.EntireColumn.AutoFit
End With
End Sub
Typically, an employee's name is a text string. You should be able to combine single quotes (aka 'ticks') with the double quotes wrapped around your entire SQL statement in order that you do not have to deal with quotes inside quotes strings.
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE [Employee Name] LIKE '" & Sheets("PDA").Range(C3).value & "';"
With Bob in Sheets("PDA").Range(C3), this should read as,
SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE [Employee Name] LIKE 'Bob';
I usually 'pattern match' with the LIKE operator but for all intents and purposes, LIKE is the same as equals.
You are passing the query as a string. As it stands now, your query looks like this (assuming the name in cell C3 is Tom Smith
:
SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] = Tom Smith
Looking at that, you can probably see that it would fail in SQL because it should read (take note of the single quotes around the name):
SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] = 'Tom Smith'
So, change the query
declaration to:
query = "SELECT DISTINCT [Client Name] FROM [Execution Report$] WHERE
[Employee Name] ='" & Sheets("PDA").Range(C3).value & "'"
Does that fix the problem?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.