具有多个连接和 SQL 查询的一个 RecordSet

One RecordSet with multiple Connections & SQL Querys

我有一个 VBA 应用程序,它调用多个工作表并为每个工作表获取一组数据。所有获得的信息必须以单个变体矩阵结束。

我想到了几种解决方案。它们是:

  1. 第一个,加入记录集只得到一个。
  2. 第二个是依次将每个 RecordSet 转储到 单矩阵

两种方案好像都不是方案... 这是解决方案编号 1 的代码:

Sub Test()
Dim RS01 As ADODB.Recordset
Dim RS02 As ADODB.Recordset
Dim Query As String
Dim FField As Variant
Dim Pair As Variant
Dim Pairs As Variant
Dim MFTE() As Variant
Dim Temp() As Variant
Dim Rows As Long
Dim Row As Long
Dim Column As Long
Dim Connection As String
'Looping throught the pairs
Pairs() = Array("EURAUD", "EURCAD")
For Each Pair In Pairs
    Select Case Par
        Case "EURAUD"
            Query = _
                "SELECT [FE], [HO], [AP], [MAX], [MIN], [CIE], [PAR]" & _
                "FROM [EURAUD$]" & _
                "WHERE (FE >=" & Date1 & ") and (FE <=" & Date2 & ")"
            Connection = _
                "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=File Number 1;" & _
                "Extended Properties=Excel 12.0"
            Set RS01 = New ADODB.Recordset
            RS01.Open Query, Connection, adOpenForwardOnly, adLockReadOnly
        Case "EURCAD"
            Query = _
                "SELECT [FE], [HO], [AP], [MAX], [MIN], [CIE], [PAR]" & _
                "FROM [EURCAD$]" & _
                "WHERE (FE >=" & Date1 & ") and (FE <=" & Date2 & ")"
            Connection = _
                "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=File Number 2;" & _
                "Extended Properties=Excel 12.0"
            Set RS02 = New ADODB.Recordset
            RS02.Open Query, Connection, adOpenForwardOnly, adLockOptimistic
    End Select
Next Pair
'Joining RS01 & RS02
RS01.MoveFirst
Do Until RS01.EOF
    RS02.AddNew
    For FField = 0 To RS01.Fields.Count - 1
        RS02.Fields(FField).Value = RS01.Fields(FField).Value
    Next FField
    RS02.Update
    RS01.MoveNext
Loop
'Dumping data into 1st variant Array
Do Until RS07.EOF
    Temp() = RS07.GetRows
Loop
'Transpose data into 2nd variant Array
Rows = RS07.RecordCount
ReDim MFTE(Rows, 7) As Variant
For Row = LBound(Temp, 2) To UBound(Temp, 2)
    For Column = LBound(Temp, 1) To UBound(Temp, 1)
        MFTE(Row, Column) = Temp(Column, Row)
    Next Column
Next Row
End Sub

使用这个解决方案我遇到了一些问题:

  1. 最终的 RecordSet 混合了第一个和第二个 RecordSets
  2. 第一个变量数组需要转置

那么,有更好的解决方案吗?

我仍然会推荐 "CopyFromRecordset",其中涉及一些编码,但我认为该过程不会显着减慢,可能只有几分之一秒