Hey All,
I need some code for the following
I want to be able to get data from a table in access but with criteria. The criteria will be found lets say on Cell A1. I use the following code to get the data from my access table, but the code below brings me back everything that is in the table. I would only need the data for 1 entry at a time, that entry would be found in cell A1, I have been reading online and I think it involves running an SQL query with excel but I have no idea how to write code for that. Any help would be greatly appreciated.
Private Sub CommandButton1_Click()
'This sub will download the information in the database
'NOTE the worksheet and the database should be in the same folder.
'Otherwise change the path
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stDB As String, stSQL1 As String
Dim wsBlad1 As Worksheet
Dim rSlutetA As Range, rSlutetR As Range 'My first column is A and my last column is R
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
Set wsBlad1 = ThisWorkbook.Worksheets("Feuil1")
Application.ScreenUpdating = False
'Path to database Note that the database should be in the same folder as this worksheet
stDB = ThisWorkbook.Path & "\" & "Database.mdb"
'Shows all elevators - objects
stSQL1 = "Select * FROM Table1"
'Remove old information
wsBlad1.Range("A1").CurrentRegion.Clear
'Create connection to database and open sql
cnt.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & "W:\CamCMC\CE\Scorpion\Database.mdb" & ";"
rst.Open stSQL1, cnt
Sheet1.Select
'Set rSlutetA = Feuil1.Range(Range("A2"), Range("A65536").End(xlUp)) 'Range A2 to the end of column A
'Set rSlutetR = Feuil1.Range(Range("R2"), Range("R65536").End(xlUp)) 'Range R2 to the end of column R
'Write field name
'Range("A1").Value = "Column heading"
'Range("B1").Value = "Column heading "
'Range("C1").Value = "Column heading"
'Range("D1").Value = "Column heading"
'Add as many columns as you want and you can skip this if you don't need the headings
Range("A1:R1").Font.FontStyle = "Bold" 'Makes heading bold
'Information copied to worksheet
wsBlad1.Cells(2, 1).CopyFromRecordset rst
'Remove old information, sort and close connection
wsBlad1.Select
'Sorting descending order in column A
' Range(rSlutetA, rSlutetR).Sort Key1:=Range("B2"), Order1:=xlDescending, Header:= _
'xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
'DataOption1:=xlSortTextAsNumbers
cnt.Close
Set cnt = Nothing
ThisWorkbook.Worksheets("Feuil1").Select
End Sub
Bookmarks