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
上面的代码成功地将数据返回到记录集中但是当尝试保存到数组时它会抛出错误..任何人都可以告诉出错了什么?
感谢您的时间!!
答案 0 :(得分:1)
错误是因为您只选择了1列。所以你的记录集只包含1列。您必须根据您的代码选择5列。
要使代码生效,您必须在查询中选择5列。否则,如果您只添加1列,那么它将在str(1) = rs(2)
如果要打印记录集到str数组的所有记录,则必须循环记录集。另外我建议没有固定大小的数组。因此,请将代码从Dim str(5)
更改为Dim str()
现在循环记录集
For i = 1 to rs.RecordCount
str(i) = rs(0)
next