I'm using excel to run sql query and i want to refer the WHERE command to a specific cell in excel. For example, my code is:
SELECT [Value]
FROM [Sheet1$]
WHERE [ClientID]=2>
Instead of 2, i went to refer to specific cell in excel, suppose T1
how can I write that query?
Thanks,
Sharon
I try to write the cell instead of 2 (T1), but it doesn't work
I'm using excel to run sql query and i want to refer the WHERE command to a specific cell in excel. For example, my code is:
SELECT [Value]
FROM [Sheet1$]
WHERE [ClientID]=2>
Instead of 2, i went to refer to specific cell in excel, suppose T1
how can I write that query?
Thanks,
Sharon
I try to write the cell instead of 2 (T1), but it doesn't work
Share edited Mar 4 at 10:32 jarlh 44.8k8 gold badges50 silver badges67 bronze badges asked Mar 4 at 10:20 SharonSharon 232 bronze badges 1- WHERE is used to choose row. The column/cell is chosen by SELECT. – jarlh Commented Mar 4 at 10:33
2 Answers
Reset to default 0When you use SQL
queries in Excel
you can't directly reference a cell.
However, there are some ways to solve your issue, each depends on the desired automatization level.
- Almost manually - using
Microsoft Query
Write query like this and run, thenExcel
will prompt you to enter a valueSELECT [Value] FROM [Sheet1$] WHERE [ClientID] = ?
- Half manually - using
Power Query
(Get and Transform): Load your table intoPower Query
; create a named range for T1 (Formulas -> Define Name); load this named range intoPower Query
; modify theSQL Query
to filter based on this value:
- use
Power Query
to join tables - filter them based on the value from named range
- Automatically - using dynamic query with
VBA
(which will automatically pull the value from T1 into your SQL query)Sub RunQuery() Dim conn As Object Dim rs As Object Dim sql As String Dim clientID As String ' Get value from cell T1 clientID = Sheets("Sheet1").Range("T1").Value ' Construct SQL query dynamically sql = "SELECT [Value] FROM [Sheet1$] WHERE [ClientID] = " & clientID ' Create connection Set conn = CreateObject("ADODB.Connection") conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";" ' Run query Set rs = conn.Execute(sql) ' Output results (example: paste in column A) Sheets("Sheet1").Range("A2").CopyFromRecordset rs ' Cleanup rs.Close conn.Close Set rs = Nothing Set conn = Nothing End Sub
Simply useing direct cell reference:
SELECT [Value]
FROM [Sheet1$]
WHERE [ClientID] = T1
or
SELECT [Value]
FROM [Sheet1$]
WHERE [ClientID] = [T1]