-1
Sub TEST()

Dim str(5)

    Set cnn = New ADODB.Connection
    Set rs = New ADODB.Recordset

If cnn.State = adStateOpen Then cnn.Close
    cnn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & _
    ActiveWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    cnn.Open

If rs.State = adStateOpen Then rs.Close
    rs.CursorLocation = adUseClient

strSQL = "SELECT DISTINCT ProductSubcategoryKey FROM [INSERT$] ORDER BY ProductSubcategoryKey DESC"

    rs.Open strSQL, cnn, adOpenKeyset, adLockOptimistic

'results are
'45
'40
'30
'34
'32

str(0) = rs(0)
str(1) = rs(1) 'Error occurs here
str(1) = rs(2)
str(2) = rs(3)
str(3) = rs(4)

Debug.Print str(0)
Debug.Print str(1)
Debug.Print str(2)
Debug.Print str(3)
Debug.Print str(4)

End Sub

the above code successfully returns the data into record set but when try to save into array it throws error.. can any one tell what's went wrong ?

Thanks for your time !!

user3114645
  • 57
  • 3
  • 16

1 Answers1

1

The error is because you have only selected 1 column. So your recordset includes only 1 column. You have to select 5 columns as per your code.

For your code to work you have to select 5 columns in your query. Otherwise if you just add 1 more column then it will fail on line below str(1) = rs(2)

If you want to print all records from recordset to str array then you have to loop through recordset. Also i would suggest to not have fixed size array. So change in your code from Dim str(5) to Dim str()

Now loop on recordset

For i = 1 to rs.RecordCount
   str(i) = rs(0)
next
DevelopmentIsMyPassion
  • 3,541
  • 4
  • 34
  • 60