【问题标题】:ADODB Connections and recordset in shared workbook共享工作簿中的 ADODB 连接和记录集
【发布时间】:2014-09-23 19:56:46
【问题描述】:

我可以在共享工作簿中使用 ADODB.Connections 和 ADODB.Recordset。我尝试运行宏,但出现运行时错误:外部表不是预期格式。部分代码有效。代码:

Option Explicit

Sub proc()

Dim CnExcel As ADODB.Connection
Dim RstExcel As ADODB.Recordset
Dim user As String

Application.EnableEvents = False

user = Environ("USERNAME") 'that's working

    Range("A2").Select 'that's working
    Range(Selection, Selection.End(xlToRight)).Select 'that's working
    Range(Selection, Selection.End(xlDown)).Select 'that's working
    Selection.ClearContents 'that's working

Set CnExcel = New ADODB.Connection

With CnExcel
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .Mode = adModeRead
    .CursorLocation = adUseClient
    .Properties("Data Source") = "C:\MB_Form.xlsm"
    .Properties("Extended Properties") = ("Excel 8.0;HDR=Yes;IMEX=1")
    .Open
End With

Set RstExcel = New ADODB.Recordset
RstExcel.Open "SELECT * FROM [Arkusz1$]", CnExcel

Dim i As Integer
i = 2

Do Until RstExcel.EOF
    If Not IsNull(RstExcel.Fields("PESEL").Value) Then
        Cells(i, 1).Value = RstExcel.Fields("ID").Value
        Cells(i, 2).Value = RstExcel.Fields("Name").Value
        Cells(i, 3).Value = RstExcel.Fields("City").Value
        i = i + 1
    End If
    RstExcel.MoveNext
Loop

CnExcel.Close

End Sub

谢谢!

【问题讨论】:

    标签: excel adodb vba


    【解决方案1】:

    您应该使用 ACE OLEDB 驱动程序并将 Excel 12.0 宏指定为类型:

    With CnExcel
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .Mode = adModeRead
        .CursorLocation = adUseClient
        .Properties("Data Source") = "C:\MB_Form.xlsm"
        .Properties("Extended Properties") = "Excel 12.0 Macro;HDR=Yes;IMEX=1"
        .Open
    End With
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-24
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多