VBA ADO查询中的OPENROWSET

时间:2017-10-28 16:30:21

标签: sql vba ado

我正在尝试在VBA程序中配置SQL UPDATE查询。

基本上,我从已关闭工作簿中的表更新当前工作簿中的表。仅当源工作簿是.xls文件时,使用以下查询才能正常工作:

Sub UPDATEQUERY(SourcePath As String, SourceSheet As String, TargetSheet As String, _
Columns As String, Filter As String)

    Dim Cn As ADODB.Connection
    Dim QUERY_SQL As String
    Dim CHAINE_HDR As String
    Dim STRCONNECTION As String

    CHAINE_HDR = "[Excel 8.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=1;Extended Properties='HDR=YES;'] "

    Set Cn = New ADODB.Connection

    QUERY_SQL = _
    "UPDATE [" & TargetSheet & "$] INNER JOIN (SELECT * FROM [" & SourceSheet & "$] " & _
    "IN '" & SourcePath & "' " & CHAINE_HDR & ") t2 " & _
    "ON [" & TargetSheet & "$].id = t2.id " & _
    "SET [" & TargetSheet & "$].ColA = t2.ColA "

    STRCONNECTION = _
    "Driver={Microsoft Excel Driver (*.xls)};" & _
    "DriverId=790;" & _
    "Dbq=" & ThisWorkbook.FullName & ";" & _
    "DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"


    Cn.Open STRCONNECTION
    Cn.Execute (QUERY_SQL)

    '--- Fermeture connexion ---
    Cn.Close
    Set Cn = Nothing

End Sub

为了使用.xlsx文件作为源文件,我想使用我用来连接到当前wb的相同提供者/驱动程序连接到源,即MSDASQL.1而不是Microsoft.ACE.OLEDB。 12.0。确实如果我只设置了CHAINE_HDR'到Excel 12.0我找不到#34; ISAM驱动程序"。

要实现这一点,我尝试使用OPENROWSET这样:

Sub UPDATEQUERY(SourcePath As String, SourceSheet As String, TargetSheet As String, _
Columns As String, Filter As String)

    Dim Cn As ADODB.Connection
    Dim QUERY_SQL As String
    Dim STRCONNECTION As String
    Dim STRCONNECTION_SOURCE As String


    STRCONNECTION_SOURCE = _
    "'MSDASQL.1'," & _
    "'Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=" & SourcePath & ";'," & _
    "'SELECT * FROM [Data$]'"

    Set Cn = New ADODB.Connection

    QUERY_SQL = _
    "UPDATE [" & TargetSheet & "$] INNER JOIN (SELECT * FROM OPENROWSET(" & STRCONNECTION_SOURCE & ")) t2 " & _
    "ON [" & TargetSheet & "$].id = t2.id " & _
    "SET [" & TargetSheet & "$].ColA = t2.ColA "

    STRCONNECTION = _
    "Driver={Microsoft Excel Driver (*.xls)};" & _
    "DriverId=790;" & _
    "Dbq=" & ThisWorkbook.FullName & ";" & _
    "DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"


    Cn.Open STRCONNECTION
    Cn.Execute (QUERY_SQL)

    '--- Fermeture connexion ---
    Cn.Close
    Set Cn = Nothing

End Sub

但是我从第&#34条中得到" Synthax错误。

如何正确设置我的SQL查询?

由于

1 个答案:

答案 0 :(得分:1)

首先,OPENROWSET是您的链接引用的Microsoft SQL Server方法(即TSQL)。此类查询只能在SQL Server查询中运行。它不是Jet / ACE SQL引擎(您当前使用的)方法。所以你让你的数据库混乱了。类似地,Oracle方法在Postgres数据库中不起作用。

是的,ACE 12.0提供商可以连接旧的 .xls 和当前的 .xlsx 文件,就像旧的MS Access一样(Office同级到MS) Excel) .mdb 和当前 .accdb 文件。只需将版本更改为Excel 8.0;Excel 12.0 Xml;

实际上,您甚至不需要使用以下格式在内联SQL命令中指定 Provider

...INNER JOIN [Excel 12.0 Xml;HDR=Yes;Database=C:\Path\To\Excel\File.xlsx].[SHEETNAME$]

使用MS Access(强烈建议数据库需求,并且在所有Windows机器上都可用,无论是否安装MSAccess.exe应用程序),您都不需要指定Excel参数:

...INNER JOIN [C:\Path\To\Access\File.mdb].[TABLENAME]

...INNER JOIN [C:\Path\To\Access\File.accdb].[TABLENAME]