0

Any help with this issue is greatly appreciated.

I am trying to retrieve from Access, by means of Select, multiple values with the same ID and have it pasted into an Excel sheet. I am running the code from Excel VBA.

The query I am using to retrieve said values is:

SELECT Role 
FROM Roles 
WHERE App_ID=(SELECT ID FROM Apps WHERE NAME='app name');

which is assigned to a variable and afterwards executed by using Set variable = cn.Execute(variable). The problem is that this query, executed from Excel VBA, returns only the first value found. Now, if I run this query from Access it returns every value with the ID for the specified app.

I have tried tried using INNER JOIN, IN, HAVING, etc. but it just wont retrieve all of the values into Excel. Like I said, the query works fine when used in Access so I know this must be limitation in Excel.

Thank you for any help you guys can provide.

2 Answers 2

1

Assuming you are using ADODB in Excel, keep in mind that the Execute function returns a Recordset. You can loop through the Recordset to see the additional rows.

Set rng = ActiveSheet.Range("A2")
Set rst = cn.Execute(strSQL)

With rst
    Do While Not .EOF
        rng = CStr(!Role)
        Set rng = rng.Offset(1)
        .MoveNext
    Loop
End With
Sign up to request clarification or add additional context in comments.

1 Comment

I think the OP wants all records written to their spreadsheet. Can you expand on this to include that piece?
1
'Applies to Access 2010
'Reference Microsoft ActiveX Data Objects 6.1 Library

Dim strSQL As String
Dim strDBPathName As String
Dim strConProvider As String
Dim strPersist As String
Dim conADODB As ADODB.Connection
Dim rsADODB As ADODB.Recordset

Set conADODB = New ADODB.Connection
strConProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"

'Database path name
strDBPathName = "Data Source=C:\Temp\Database.accdb;"

strPersist = "Persist Security Info=False;"

With conADODB
    .ConnectionString = strConProvider & strDBPathName & strPersist
    .Open
End With

strSQL = "SELECT Role FROM Roles WHERE App_ID=(SELECT ID FROM Apps WHERE NAME='app name')"
Set rsADODB = New ADODB.Recordset

With rsADODB
    .Open strSQL, conADODB, adOpenStatic, adLockPessimistic

    If Not (.EOF And .BOF) Then
'Range of spreadsheet to paste records
        Cells(1, 1).CopyFromRecordset rsADODB
    End If

    .Close
End With

Set rsADODB = Nothing
conADODB.Close
Set conADODB = Nothing

2 Comments

Just for future reference: Try adding some comments to your posts so the topic starter may get an idea of what you are doing. :)
Thanks waka. I appreciate the tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.