非常感谢您对此问题的任何帮助。
我试图通过Select从Access中检索具有相同ID的多个值,并将其粘贴到Excel工作表中。我正在运行Excel VBA中的代码。
我用来检索所述值的查询是:
SELECT Role
FROM Roles
WHERE App_ID=(SELECT ID FROM Apps WHERE NAME='app name');
分配给变量,然后使用Set variable = cn.Execute(variable)
执行。问题是,从Excel VBA执行的此查询仅返回找到的第一个值。现在,如果我从Access运行此查询,它将返回具有指定应用程序ID的每个值。
我尝试过尝试使用INNER JOIN,IN,HAVING等,但它只是不会将所有值都检索到Excel中。就像我说的,查询在Access中使用时工作正常,所以我知道这必须是Excel中的限制。
感谢您提供任何帮助。
答案 0 :(得分:1)
假设您在Excel中使用ADODB,请记住Execute
函数返回Recordset
。您可以循环遍历Recordset以查看其他行。
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
答案 1 :(得分: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