我有一张包含数据表
的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
。
请让我知道为什么其他记录没有复制到记录集中?
答案 0 :(得分: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
答案 1 :(得分:2)
此答案取决于Excel中提供的ODBC数据库驱动程序。
由于我的公司env,我被迫使用非常旧的Oracle ODBC驱动程序。就我而言,Recordset.RecordCount
始终是-1
。默认情况下,不支持Recordset.MoveLast
和Recordset.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)
对于我的驱动程序,这可以解决问题。但是,您的里程可能会有所不同。
答案 2 :(得分:0)
我遇到了同样的问题。
仅替换
set rst = conn.execute("SELECT * FROM SOMETABLE;")
与
call rst.open("SELECT * FROM SOMETABLE;", conn)
那问题就解决了
但是,我不知道为什么。