4

我有一个 Excel 表,其中包含类似数据的表格

strSQL = "SELECT S.FIELD_NAME1,S.FIELD_NAME2,S.FIELD_NAME3 from [SourceData$A1:IV6] S"

Dim cn as ADODB.Connection
Dim rs as ADODB.Recordset
cn.Open strCon
Set rs = CmdSqlData.Execute()
Worksheets("SourceData").Cells.ClearContent
Worksheets("AnswerData").Cells(2, 1).CopyFromRecordset rs

结果:
只有第一行和其他记录被忽略。

我试过下面的查询。,

strSQL = "SELECT COUNT(*) from [SourceData$A1:IV6] S"

结果给出了5

请让我知道为什么其他记录没有复制到记录集中?

4

3 回答 3

3

这是一个成功粘贴记录集的子例程。

请注意,它粘贴到的范围与通过 intMaxRow 和 intMaxCol 变量的记录集大小相同:

Sub sCopyFromRS()
'Send records to the first
'sheet in a new workbook
'
Dim rs As Recordset
Dim intMaxCol As Integer
Dim intMaxRow As Integer
Dim objXL As Excel.Application
Dim objWkb As Workbook
Dim objSht As Worksheet
  Set rs = CurrentDb.OpenRecordset("Customers", _
                    dbOpenSnapshot)
  intMaxCol = rs.Fields.Count
  If rs.RecordCount > 0 Then
    rs.MoveLast:    rs.MoveFirst
    intMaxRow = rs.RecordCount
    Set objXL = New Excel.Application
    With objXL
      .Visible = True
      Set objWkb = .Workbooks.Add
      Set objSht = objWkb.Worksheets(1)
      With objSht
        .Range(.Cells(1, 1), .Cells(intMaxRow, _
            intMaxCol)).CopyFromRecordset rs
      End With
    End With
  End If
End Sub

使用该示例作为模型,我会为您的代码尝试这样的事情:

strSQL = "SELECT S.FIELD_NAME1,S.FIELD_NAME2,S.FIELD_NAME3 from [SourceData$A1:IV6] S"

Dim cn as ADODB.Connection
Dim rs as ADODB.Recordset
Dim intMaxCol as Integer
Dim intMaxRow as Integer

cn.Open strCon
Set rs = CmdSqlData.Execute()
intMaxCol = rs.Fields.Count
'- MoveLast/First to get an accurate RecordCount
rs.MoveLast 
rs.MoveFirst

If rs.RecordCount > 0 then
    '-thought you could put the MoveLast/First here but maybe not.
    intMaxRow = rs.RecordCount
    With Worksheets("AnswerData")
        .Range(.Cells(2,1),.Cells(intMaxRow+1,intMaxColumn)).CopyFromRecordset rs
    End With
End If
于 2012-07-11T12:05:20.190 回答
2

这个答案取决于您在 Excel 中可用的 ODBC 数据库驱动程序。

由于我的公司环境,我被迫使用一个非常旧的 Oracle ODBC 驱动程序。就我而言,Recordset.RecordCount总是-1. 默认情况下,Recordset.MoveLastRecordset.MoveFirst支持。像原来的问题一样,调用Excel.Range.CopyFromRecordset(Recordset)也只写一行。

您可能需要以ADODB.Recordset不同方式配置您的。试试这个代码:

Dim dbConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rng As Excel.Range
Dim rowCount As Long

' TODO: Init your dbConn here.
' TODO: Init your rng here.

Set rs = New ADODB.Recordset
' http://www.w3schools.com/ado/prop_rs_cursortype.asp
rs.CursorType = ADODB.CursorTypeEnum.adOpenKeyset
rs.Open sql, dbConn
rowCount = rng.CopyFromRecordset(rs)

对于我的驱动程序,这解决了这个问题。但是,您的里程可能会有所不同。

您可以在此处阅读有关 ADO 游标类型的更多信息

于 2013-03-28T03:54:25.287 回答
1

我遇到同样的问题。

仅替换

set rst = conn.execute("SELECT * FROM SOMETABLE;") 

call rst.open("SELECT * FROM SOMETABLE;", conn)

然后问题就解决了

但是,我不知道为什么。

于 2018-11-14T10:34:11.830 回答