【问题标题】:Clone existing recordset to excel recordset将现有记录集克隆到 Excel 记录集
【发布时间】:2009-09-23 11:11:20
【问题描述】:

我有一个记录集,其中包含导入 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

谢谢。

【问题讨论】:

    标签: excel asp-classic vbscript adodb recordset


    【解决方案1】:

    当你这样做时:-

    Set excelRecordset = recordset.clone
    

    您将在 Excel 电子表格上打开(并关闭)的记录集的引用替换为对新记录集的引用。这个新记录集无论如何都没有连接到 Excel 电子表格。

    使用记录集,您实际上别无选择,只能通过源记录集For Each、目标上的AddNew、将每个字段从源分配到目标和Update

    【讨论】:

    • 这就是我害怕的。对于每个循环,谢谢。 :)
    【解决方案2】:

    Excel Range 对象有一个 CopyFromRecordset 方法应该可以完成这项工作。如果您可以创建一个Excel.Application 对象并打开您要写入的工作簿,那么您应该可以使用它。

    因此,如果您现有的记录集名为 rs 并且已被填充,则 VBA 中的代码将是:

    Worksheets("SHEET1").Cells(2, 1).CopyFromRecordset rs
    

    然后您可以遍历 rs.Fields 以填写字段名称

    Dim fld As Field
    Dim i As Integer
    i = 1
    With Worksheets("SHEET1")
        For Each fld in rs.Fields
            .Cells(1, i).Value = fld.Name
            i = i + 1
        Next fld
    End With
    

    但不确定将其转换为您的场景有多容易。

    或者,如果您使用的驱动程序可以使用它,您可能需要查看this Knowledge Base article 中描述的SELECT INTOINSERT INTO 语法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多