VBA Dynamic WHERE clause in a SQL statement

Shadow777

New Member
Joined
Nov 10, 2019
Messages
4
Hi,

I'm trying to connect to an SQLite database that contains financial information about various companies. The code will then put the information into a worksheet for me. Currently I am having to hard code the symbol of the company that I am wanting to search in the database for. This works, and returns the headers and correct data (although it doesn't return the actual symbol for some reason).

I want to make it so that I can filter a dropdown and the code will reference the particular symbol that I have selected and search for that. I have attempted this and have managed to get it so that no errors are produced, however it will only get the headers but fails to get any data.

I have set the named cell as M1 on Sheet2.

VBA Code:
Sub GetData()

Dim conn As ADODB.Connection
Dim TestData As ADODB.Recordset
Dim icols As Integer

Dim code As Range

Set code = Worksheets("Sheet2").Range("M1")
Dim r As Variant
r = code.Value

Set conn = New ADODB.Connection
Set TestData = New ADODB.Recordset

conn.Open "DRIVER=SQLITE3 ODBC DRIVER;DATABASE=C:\Users\shadow\financials.db;"

strSQL = "SELECT * FROM financials WHERE Ticker= 'r'"

TestData.Open strSQL, conn

For icols = 0 To TestData.Fields.Count - 1
    Worksheets("Sheet2").Cells(1, icols + 1).Value = TestData.Fields(icols).Name
Next icols

Worksheets("Sheet2").Range("A2").CopyFromRecordset TestData
TestData.Close

Set TestData = Nothing
Set conn = Nothing


End Sub

VBA Code:
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
what sort of things is r supposed to hold
 
Upvote 0

Forum statistics

Threads
1,223,888
Messages
6,175,208
Members
452,618
Latest member
Tam84

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top