将现有记录集克隆到 Excel 记录集
我有一个记录集,其中包含导入 Excel 文件所需的所有数据。有没有一种方法可以将实时记录集克隆到打开 Excel 文件时创建的记录集?
这是我现在正在尝试的,但没有运气。
Dim connection : Set connection = Server.CreateObject("ADODB.Connection")
connection.Open "Driver={Microsoft Excel Driver (*.xls)}; DriverId=790;
Dbq=c:\MyExcel.xls;" & _
"DefaultDir=c:\; ReadOnly=False;"
Dim excelRecordset : Set excelRecordset = Server.CreateObject("ADODB.Recordset")
excelRecordset.Open "[SHEET1$]", connection, 2, 3
excelRecordset.AddNew
Set excelRecordset = recordset.clone
excelRecordset.Update
excelRecordset.Close
谢谢。
I have a recordset that contains all of the data needed to import into an Excel file. Is there a way I can clone my live recordset into the one created when I open an Excel file?
Here is what I'm trying right now with no luck.
Dim connection : Set connection = Server.CreateObject("ADODB.Connection")
connection.Open "Driver={Microsoft Excel Driver (*.xls)}; DriverId=790;
Dbq=c:\MyExcel.xls;" & _
"DefaultDir=c:\; ReadOnly=False;"
Dim excelRecordset : Set excelRecordset = Server.CreateObject("ADODB.Recordset")
excelRecordset.Open "[SHEET1$]", connection, 2, 3
excelRecordset.AddNew
Set excelRecordset = recordset.clone
excelRecordset.Update
excelRecordset.Close
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您执行此操作时:-
您将对在 Excel 电子表格上打开的记录集的引用(并且它会关闭)替换为对新记录集的引用。这个新记录集不以任何方式连接到 Excel 电子表格。
使用记录集,您实际上没有太多选择,只能通过源记录集
For Each
,在目标上AddNew
,将每个字段从源分配到目标并Update
。When you do this:-
You replace the reference to the recordset opened on the excel spreadsheet (and it closes) with a reference to new recordset. This new recordset is not in anyway connected to the excel spreadsheet.
Using recordsets you don't really have much choice but to
For Each
through the source recordset,AddNew
on the destination, assign each field from source to destination andUpdate
.Excel
Range
对象有一个CopyFromRecordset
方法来完成这项工作。如果您可以创建一个Excel.Application
对象并打开要写入的工作簿,那么您应该能够使用它。因此,如果您现有的记录集名为
rs
并且已被填充,则 VBA 中的代码将为:然后您可以迭代
rs.Fields
来填充字段名称不不过,确定将其转化为您的场景是多么容易。
或者,如果您正在使用的驱动程序提供该功能,您可能需要查看 这篇知识库文章
Excel
Range
objects have aCopyFromRecordset
method that should do the job. If you can create anExcel.Application
object and open the workbook you want to write to then you should be able to use this.So if your existing recordset is named
rs
and has already been populated, the code in VBA would be:You can then iterate over
rs.Fields
to fill in the field namesNot sure how easy that would be to translate to your scenario though.
Alternatively, if it is available with the driver you are using, you may want to look into the
SELECT INTO
andINSERT INTO
syntax described in this Knowledge Base article