VBA在运行时添加到数组

时间:2011-05-25 14:19:53

标签: vba vb6 vbscript

我试图在运行时根据记录集的结果创建一个int数组。

Do While Not rstSearchResult.EOF

 If rstSearchResult(ID) = blah Then 
  'Add this Id rstSearchResult(ID) to Array
 End If

 Call rstSearchResult.MoveNext()
Loop

我需要的是同样的结果,这会给我Array(35588, 35589, 35595)

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:6)

当我需要从Recordset复制到数组时,将数组ReDim到你想要的大小而不是在循环中重新定位它会更有效率。

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

请注意,要使RecordCount正常工作,您需要将记录集打开为静态。

rstSearchResult.Open "tblSearchResult", cnn, adOpenStatic

答案 2 :(得分:1)

当我在excel中执行VBA时,我有一个用于访问数据库的类我有一个函数将记录集返回给数组。希望以下有所帮助。

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