gpt4 book ai didi

vba - 即使 Excel 中存在多条记录,CopyFromRecordset 也仅复制并粘贴前一行

转载 作者:行者123 更新时间:2023-12-02 10:34:26 24 4
gpt4 key购买 nike

我有一个包含表格数据的 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

请告诉我为什么其他记录没有复制到记录集中?

最佳答案

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

请注意,它粘贴到的范围与通过 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

关于vba - 即使 Excel 中存在多条记录,CopyFromRecordset 也仅复制并粘贴前一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11426103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com