数组 – 最好多次ReDim数组或重新打开记录集?

我正在VBscript中编写代码,打开一个记录集对象,然后加载一个包含每个记录数据的对象的数组.我的记录集类型不支持rs.RecordCount属性,所以我需要在循环记录集时需要ReDim保留数组,或者我需要在执行计数循环后重新打开记录集,因为在计数循环之后使用rs.MoveFirst似乎工作……哪个会更快?记录集对象中最多只有7条记录,所以最多我需要多次ReDim.

这是我尝试的一种方式,但rs.MoveFirst似乎无法正常工作,请参阅注释:

Function LoadData(filter_val)
   Dim arr
   Dim rs
   'Calls function that opens the rs and returns it
   Set rs = GetRS(filter_val)

   Dim counter
   counter = 0
   Do Until rs.EOF
      counter = counter + 1
      rs.MoveNext
   Loop

   ReDim arr(counter)

   rs.MoveFirst

   For i = 0 To counter
      Set arr(i) = New obj
      'attempt to load values into the object from the recordset, but get an
      'error saying 'either BOF or EOF is true, or the current record has been deleted'
      'I tried adding If statements with MsgBox print outs checking for rs.EOF or rs.BOF
      'being true right after rs.MoveFirst, but neither evaluates to true...
   Next
End Function

这个方法有效,但我必须不断ReDim数组:

Function LoadData(filter_val)
   Dim arr
   Dim rs
   Set rs = GetRS(filter_val)

   Dim counter
   counter = 0
   ReDim arr(counter)

   Do Until rs.EOF
      Set arr(counter) = New obj

      'load data from rs into object

      rs.MoveNext

      If Not rs.EOF
         counter = counter + 1
         ReDim Preserve arr(counter)
      End If

   Loop
End Function

最佳答案 重新定尺寸阵列的表现非常出色,所以我选择了ReDim.增加数组大小的通用方法是将其初始化为空数组:

ReDim arr(-1)

然后在添加内容之前每次迭代将上边界增加1:

Do Until rs.EOF
  ReDim Preserve arr(UBound(arr)+1)
  Set arr(UBound(arr)) = New obj

  'load data from rs into object

  rs.MoveNext
Loop

这样,您不需要计数器变量来跟踪数组大小.

点赞