Excel 避免在VBA中使用ADO记录集检索“echo”打印

Excel 避免在VBA中使用ADO记录集检索“echo”打印,excel,vba,odbc,ado,recordset,Excel,Vba,Odbc,Ado,Recordset,我不是VBA和excel宏的专家,但我需要执行数据库中的SQL宏。 此宏在其SQL定义中执行一些“echo”操作,在开始时为4“echo” 最后是2个“echo”,然后SQL宏检索18列。 删除“echo”检索性能良好,但我需要在SQL代码中维护“echo”,因为此宏是由系统自动创建的。 为了从外部源检索数据,我使用ADO记录集,如下所示: 'If the recordset is empty If (rs.EOF And rs.BOF) Then iReply = MsgBox(Pro

我不是VBA和excel宏的专家,但我需要执行数据库中的SQL宏。 此宏在其SQL定义中执行一些“echo”操作,在开始时为4“echo” 最后是2个“echo”,然后SQL宏检索18列。 删除“echo”检索性能良好,但我需要在SQL代码中维护“echo”,因为此宏是由系统自动创建的。 为了从外部源检索数据,我使用ADO记录集,如下所示:

'If the recordset is empty
If (rs.EOF And rs.BOF) Then
    iReply = MsgBox(Prompt:="No data retrieved", _
        Buttons:=vbOKOnly, Title:="Error")
Else 'If the recordset contains data
    rs.MoveFirst
    Row = 2
    Do While (rs.EOF = False And rs.BOF = False)         
        p = rs.GetRows
        Sheet2.Range("A" & Row).Value = p(0, 0)
        Sheet2.Range("B" & Row).Value = p(1, 0)
        Sheet2.Range("C" & Row).Value = p(2, 0)
        Sheet2.Range("D" & Row).Value = p(3, 0)
        Sheet2.Range("E" & Row).Value = p(4, 0)
        Sheet2.Range("F" & Row).Value = p(5, 0)
        Sheet2.Range("G" & Row).Value = p(6, 0)
        Sheet2.Range("H" & Row).Value = p(7, 0)
        Sheet2.Range("I" & Row).Value = p(8, 0)
        Sheet2.Range("J" & Row).Value = p(9, 0)
        Sheet2.Range("K" & Row).Value = p(10, 0)
        Sheet2.Range("L" & Row).Value = p(11, 0)
        Sheet2.Range("M" & Row).Value = p(12, 0)
        Sheet2.Range("N" & Row).Value = p(13, 0)
        Sheet2.Range("O" & Row).Value = p(14, 0)
        Sheet2.Range("P" & Row).Value = p(15, 0)
        Sheet2.Range("Q" & Row).Value = p(16, 0)
        Sheet2.Range("R" & Row).Value = p(17, 0)
        Row = Row + 1
    Loop
End If
事实上,对于SQL宏中的“echo”,只有第一个“echo”被检索并打印在我的excel工作表的第一列中,然后它不会检索任何其他内容,其他的“echo”和我感兴趣的18列数据都不会检索。 我尝试使用记录集MoveNext和Move方法移动到第5个位置,因为我认为第5个位置对应于前18列数据,因为我在开始时有4个“echo”,但它不起作用: 即使移动到第二个位置也不起作用,因此我得出结论,在我的记录集中,只有一个条目对应于第一个“echo”,然后记录集达到其EOF并退出循环。 我的代码中是否有某种方法或更改可以避免检索SQL宏生成的“echo”


提前谢谢

这里可能有个错误,但我想你想要这样的东西。您只想调用GetRows一次,因为在调用它之后,这与说MoveLast是一样的。这里的想法是将记录集转储到一个数组中,然后循环遍历第二维行的每个元素。在其中,循环第4列到第21列,我认为这跳过了你的回声

Dim p as Variant
Dim i as Long
Dim j as Long

'If the recordset is empty
If (rs.EOF And rs.BOF) Then
    iReply = MsgBox(Prompt:="No data retrieved", _
        Buttons:=vbOKOnly, Title:="Error")
Else 'If the recordset contains data
   'just fetch it once
   p = rs.GetRows
   'loop through the rows
   For i = Lbound(p,2) to Ubound(p,2)
      'loop through the columns that don't have "echo"
      For j = 4 to 21
        Sheet2.Cells(i,j-2).Value = p(j, i)
      Next j
   Next i
End If

谢谢Doug的帮助,但它没有起作用…事实是,即使使用您的代码,rs也只包含第一个“echo”打印,然后没有其他内容…我尝试调整它,但目前没有成功…:D