Recordset to array?

Jaymond Flurrie

Well-known Member
Joined
Sep 22, 2008
Messages
868
I'm using Excel 2010. I know how to put recordset into a range. I would need to put recordset into an array. This is the code I use to put it into a range:

Code:
    Set rsData = New ADODB.Recordset
    rsData.Open strSQL, strConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

    If Not rsData.EOF Then
        Range("A1").CopyFromRecordset rsData
    Else
        MsgBox "No records returned.", vbCritical
    End If
And it works, returns 14 results (14 rows, 1 column). The difference should be on the last line, but how?

Code:
vSRA = rsData.GetRows(14) 'vSRA is a variant
Range("A1") = vSRA(1, 1)
gives subscript out of range, so does

Code:
vSRA = rsData.GetRows
Range("A1") = vSRA(1)
What's wrong? Do I need some to alter something else than that last row (where I copy it from the recordset to a range)?
 
Last edited:

Some videos you may like

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).

Jaymond Flurrie

Well-known Member
Joined
Sep 22, 2008
Messages
868
Also, when I want to query again, should I do

Code:
    Set rsData = Nothing
    Set rsData = New ADODB.Recordset

or is that first line needless?
 

ukmikeb

Well-known Member
Joined
Jul 10, 2009
Messages
2,757
Hi

To load the results of your query into an array use :-

Code:
vSRA = rsData.GetRows()

then to find the number of records that you have retrieved -

Code:
returnedRows = UBound(vSRA, 2)

then filling the cells -

Code:
Range("A1") = vSRA(0, 0)

The records are stored starting at zero.

If you are retrieving a different set of records it is always good housekeeping to set the recordset to "Nothing".

hth

Mike
 

Watch MrExcel Video

Forum statistics

Threads
1,109,087
Messages
5,526,772
Members
409,720
Latest member
Antwain

This Week's Hot Topics

Top