I have a table that contains data that I am trying to import into a spreadsheet control on a userform in vba/excel.
The results will be viewed by an end user, so I have set the value of the header cells on initialization as opposed the the column headings from the sql table.
My query looks something like this
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "Provider=SQLOLEDB;Data Source=mysource;Initial Catalog=mydatabase;User Id=myusername;Password=mypassword;QuotedID=No"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM WOFT_tbl_clients WHERE userid = '" & UserId.Value & "';")
If Not rs.EOF Then
/////////////////
/something here!/
/////////////////
Else
MsgBox "Error: No records returned.", vbCritical
End If
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
What I am trying to do is get the output of selected columns from the database and be able to feed them into whatever colomn I like on the spreadsheet control.
So in effect I would somehow like a loop that allows me to output the resultset of columns id, name and userid into the spreadsheet control starting from row 2. My database also contains many other columns which are not needed in this spreadsheet, but will be needed for another spreadsheet control on the same userform, some of which will appear on both.
What I would like to be able to do is have each column in its own recordset, so I could have something like ids stored in a id recordset which I could then use in column A in spreadsheet control 1, and colomn 6 in spreadsheet control 2?
I hope this makes sense! I am using Excel 2010
To have each data column from one table in an extra recordset would lead you to isolated data lists, which wouldn’t follow any logic of a relational database model. If the data indeed is isolated in the way, that
idis a list,nameis another list and so on, living in the same table, then – forgive me – your database model is quite bad.If you nevertheless want to get only certain columns from your SQL database, specify them in the SQL statement:
To loop through every record the recordset object returns, use a do-until loop like this. Don’t forget the
MoveNext, or it may result in an endless loop.I hope this is what you needed. Feel free to further explain, if I didn’t understand your needs correctly.