Save results from a query to an array

1

Good afternoon!

I need to get the results of this query:

sql = "SELECT controle.ID FROM controle WHERE BP = '" & controlectform.nmbpbox.Value & "';"

And save to an array. Subsequently I will do a for each in that array and I will use the results stored in a new query.

For each I have done but the data is not inserted into my array, so the query only runs the first time.

The full code below follows.

Function InsereDados()

    Dim vArray As Variant
    Dim vContador As Integer
    Dim cn  As ADODB.Connection
    Dim rs  As ADODB.Recordset
    Dim arrid() As String
    Dim toid As Variant


    Set cn = New ADODB.Connection

    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & enderecoDB & ";Jet OLEDB:Database"

    cn.Open

    Set rs = New ADODB.Recordset

    sql = "SELECT controle.ID FROM controle WHERE BP = '" & controlectform.nmbpbox.Value & "';"

    rs.Open sql, cn

    For i = 1 To rs.RecordCount

    arrid(0) = rs(0)

    Next

    For Each ID In arrid

    Call SelectIDENT
    Call SelectBENEFIT
    Call SelectBP
    Call SelectCPF
    Call SelectNome
    Call SelectADM
    Call SelectFilial
    Call SelectSOLICITANTE
    Call SelectDTSOLIC
    Call SelectRECEBIMENTO
    Call SelectENVIO
    Call SelectRETIROU
    Call SelectMINUTA
    Call SelectCARTAO

    vArray = Array("", SelectIDENT, SelectBENEFIT, SelectBP, SelectCPF, SelectNome, SelectADM, SelectFilial, SelectSOLICITANTE, _
        SelectDTSOLIC, SelectRECEBIMENTO, SelectENVIO, SelectRETIROU, SelectMINUTA, SelectCARTAO)

    count = 2

        With Worksheets("Planilha1")
           For vContador = 1 To UBound(vArray)
           .Cells(count, vContador).Value = vArray(vContador)
            Next vContador
        End With
    count = count + 1

   Next

End Function
    
asked by anonymous 03.04.2017 / 21:40

1 answer

1

Your problem is in using the recordcount property as a check for your [FOR]. The recordcount will only have information after you go through the recordset. As a solution I suggest:

option 1: Before doing [FOR] . . .     rs.movelast     rs.movefirst . . .

Option 2: Use the EOF (End of file) property. This property is false until it reaches the end of the recordset, ie the last line.

Another point is that as you are going to fill your array and you do not know the amount of records returned, you should resize the size of your array, in which case you should use the REDIM command.

    
09.04.2017 / 06:54