I am trying to create an int array at runtime from results of a record set.
Do While Not rstSearchResult.EOF
If rstSearchResult(ID) = blah Then
'Add this Id rstSearchResult(ID) to Array
End If
Call rstSearchResult.MoveNext()
Loop
What I need is 开发者_运维问答that same result as this will give me Array(35588, 35589, 35595)
Dim myIntArray() as Integer
Dim intDimension as Integer
intDimension = 0
Do While Not rstSearchResult.EOF
If rstSearchResult(ID) = blah Then
'Add this Id rstSearchResult(ID) to Array
REDIM PRESERVE myIntArray(intDimension)
myIntArray(intDimension) = rstSearchResult(ID)
intDimension = intDimension +1
End If
Call rstSearchResult.MoveNext()
Loop
When I need to copy from a Recordset to an array, it's a little bit more efficient to ReDim the array to the size you want beforehand instead of ReDiming it inside the loop.
Dim myIntArray() as Integer
Dim intDimension as Integer
rstSearchResult.Filter = "ID = " & blah
ReDim myIntArray(rstSearchResult.RecordCount - 1)
intDimension = 0
Do Until rstSearchResult.EOF
myIntArray(intDimension) = rstSearchResult!ID
intDimension = intDimension + 1
rstSearchResult.MoveNext
Loop
Note that for RecordCount to work you need to open the recordset as static.
rstSearchResult.Open "tblSearchResult", cnn, adOpenStatic
When I do VBA in excel I have a class I use for the DB accessing in it I have a function that returns the recordset to an array. Hope the below helps.
Public Function RSToArray(ByVal oRS, Optional ByVal iRows, Optional ByVal iStart, Optional ByVal aFieldsArray)
If iRows = 0 Then iRows = adGetRowsRest
If iStart = 0 Then iStart = adBookmarkfirst
RSToArray = "" ' return a string so user can check For (IsArray)
If IsObject(oRS) And oRS.State = adStateOpen Then
If Not oRS.BOF And Not oRS.EOF Then
If IsArray(aFieldsArray) Then
RSToArray = oRS.GetRows(iRows, iStart, aFieldsArray)
Else
If iRows <> adGetRowsRest Or iStart <> adBookmarkfirst Then
RSToArray = oRS.GetRows(iRows, iStart)
Else
RSToArray = oRS.GetRows()
End If
End If
End If
End If
End Function
精彩评论