Excel VBA:我可以在不打开目标文件的情况下查询外部Excel吗?

时间:2017-11-10 09:38:05

标签: excel vba excel-vba

我想省略行"。打开"下面但它说"当对象关闭时不允许操作",有没有方法可以查询文件而不打开文件?

Set cn = CreateObject("ADODB.Connection")
With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=" & "C:\data.xls" & ";" & _
    "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    .Open
End With
Set rs = cn.Execute("SQL statement here")

1 个答案:

答案 0 :(得分:0)

您打开连接,而不是文件本身。 因此,它真的是你需要的。 请尝试以下操作,并查看该文件未打开:

Option Explicit

Public Sub TestMe()

    Dim cn  As Object
    Dim rs  As Object

    Set cn = CreateObject("ADODB.Connection")
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & "C:\DB.xlsm" & ";" & _
        "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
        .Open
    End With

    Set rs = cn.Execute("SELECT * FROM [Sheet1$]")

    Do Until rs.EOF
        Debug.Print rs.Fields.Item(1), rs.Fields.Item(2)
        rs.MoveNext
    Loop

    'cn.Close <- you need this only if you work with some crazy guys, who do not
                'understand the open-close principle

End Sub

如果文件在许多用户之间共享,则可以使用ReadOnly连接权限(只需更改ConnectionString,如图所示):

With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=" & "C:\DB.xlsm" & ";" & _
    "Extended Properties=""Excel 12.0 Xml;HDR=YES application intent=ReadOnly"";"
    .Open
End With