JacekKotowski
New Member
- Joined
- Aug 23, 2013
- Messages
- 18
Dear Colleagues. I am trying to use ACE sql to return array from recordset. The function works well with table ranges.
Problem: the function returns the right number of records if the query returns 2 or more records. However if only one record is found, all rows are filled repetitively with this one row. This is wrong but I cannot find the reason why.
In addition, I wish my function would return column names from Recordset. I found some code, that could do it (commented out) but I have no idea how to glue it together with the array returned from recordset.
Here is the code, credits are due to the author of another solution that I am trying to adapt to my needs: Performing SQL queries on an Excel Table within a Workbook with VBA Macro
Thank you in advance for all the comments and help
Problem: the function returns the right number of records if the query returns 2 or more records. However if only one record is found, all rows are filled repetitively with this one row. This is wrong but I cannot find the reason why.
In addition, I wish my function would return column names from Recordset. I found some code, that could do it (commented out) but I have no idea how to glue it together with the array returned from recordset.
Here is the code, credits are due to the author of another solution that I am trying to adapt to my needs: Performing SQL queries on an Excel Table within a Workbook with VBA Macro
Thank you in advance for all the comments and help
Code:
Function SQL(dataRange As Range, CritA As String) As Variant
Application.Volatile
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim currAddress As String
currAddress = ActiveSheet.Name & "$" & dataRange.Address(False, False)
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM [" & currAddress & "]" & _
"WHERE [A] = '" & CritA & "' " & _
"ORDER BY 1 ASC"
rs.Open strSQL, cn
'SQL = rs.GetString
SQL = Application.Transpose(rs.GetRows)
Set rs = Nothing
Set cn = Nothing
End Function
Last edited: