Hi, does anyone know about ADO connections to Databases using VBA?
I have this code that works well.
It extracts Employee ID's and there Names from our database and lists them in columns A:C
What I want to do is list the ID's manually and get it to extract only the Names for the ID's I listed in Column A...
I am not sure how to amend this code to look at ID's listed in column A instead of extracting the whole database.
I know I need to add a "WHERE ID =" clause in the SQL but not sure how to say WHERE ID = A1, A2, etc...
Thanks.
Here's the code that works at extracting the whole database (it's not mine...I don't remember where on the web I found it):
Option Explicit
Sub Button1_Click()
'Defining variables
Dim cnOra As ADODB.Connection
Dim rsOra As ADODB.Recordset
Dim db_name As String
Dim UserName As String
Dim Password As String
Dim i As Long
Set cnOra = New ADODB.Connection
Set rsOra = New ADODB.Recordset
db_name = "SANDBOX_ODBC"
UserName = "SYSADM"
Password = "SYSADM"
'Making an ODBC connection according to ADO
cnOra.Open "DSN=" + db_name + ";UID=" + UserName + ";PWD=" & Password + ";"
rsOra.CursorLocation = adUseServer
'Running a query
rsOra.Open "Select ID, FIRST_NAME, LAST_NAME from EMPLOYEE", cnOra, adOpenForwardOnly
'Passing on data from the recordset to a variable or cell.
'Notice that the column name or alias is used to address
'data in the recordset.
i = 1
While Not rsOra.EOF
Worksheets("sheet1").Range("A" & i) = rsOra![ID]
Worksheets("sheet1").Range("B" & i) = rsOra![FIRST_NAME]
Worksheets("sheet1").Range("C" & i) = rsOra![LAST_NAME]
rsOra.MoveNext
i = i + 1
Wend
rsOra.Close
rsOra.Open "select sysdate from dual", cnOra, adOpenForwardOnly
While Not rsOra.EOF
Worksheets("Sheet1").Range("E2") = rsOra![sysdate]
rsOra.MoveNext
Wend
'Forgetting to close your connection will sometimes result in
'Dr.Watsons
rsOra.Close
cnOra.Close
Set rsOra = Nothing
End Sub
Bookmarks