查询表达式VBA中的语法错误(缺少运算符)

时间:2015-05-13 12:52:50

标签: excel vba excel-vba

当我想在查询表达式中运行查询时出现错误消息(语法错误(缺少运算符))。我不知道问题出在哪里。

我创建了一个宏(VBA),它应该显示我公司的所有经理级别。

列应该是这样的:

  

高级经理,董事,经理,团队领导,主管,员工。

Sub TEST()
    Application.ScreenUpdating = False

    Dim cnStr                 As String
    Dim rs                    As ADODB.Recordset
    Dim query                 As String
    Dim fileName              As String
    pom4 = "';"

    fileName = "C:\sciezka\DEU.xlsx"

    cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
            "Data Source=" & fileName & ";" & _
            "Extended Properties=Excel 12.0"


    query = "SELECT L1.[DEU1$].[Supervisor ID] AS N0, L1.[DEU1$].[Emplid] AS N1, L2.[DEU1$].[Emplid] AS N2, L3.[DEU1$].[Emplid] AS N3, " & _
            "L4.[DEU1$].[Emplid] AS N4, L5.[DEU1$].[Emplid] AS N5, L6.[DEU1$].[Emplid] AS N6, L7.[DEU1$].[Emplid] AS N7 FROM [DEU1$] L1 " & _
            "LEFT JOIN [DEU1$] L2 ON (L1.[Emplid]=L2.[Supervisor ID]) LEFT JOIN [DEU1$] L3 ON (L2.[Emplid]=L3.[Supervisor ID]) " & _
            "LEFT JOIN [DEU1$] L4 ON (L3.[Emplid]=L4.[Supervisor ID]) LEFT JOIN [DEU1$] L5 ON (L4.[Emplid]=L5.[Supervisor ID]) " & _
            "LEFT JOIN [DEU1$] L6 ON (L5.[Emplid]=L6.[Supervisor ID]) LEFT JOIN [DEU1$] L7 ON (L6.[Emplid]=L7.[Supervisor ID]) WHERE L1.[Supervisor ID] LIKE '%15981%';"

    Set rs = New ADODB.Recordset

    rs.Open query, cnStr, adOpenUnspecified, adLockUnspecified

    Cells.Clear

    Dim cell As Range, i      As Long

    With Range("A16").CurrentRegion
        For i = 0 To rs.Fields.Count - 1
            .Cells(1, i + 1).Value = rs.Fields(i).Name
        Next i
        Range("A17").CopyFromRecordset rs
        .Cells.Select
        .EntireColumn.AutoFit
    End With

    rs.Close
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:0)

我认为你只需要添加一些括号,而不是同时使用别名和实际的表名:

query = "SELECT L1.[Supervisor ID] AS N0, L1.[Emplid] AS N1, L2.[Emplid] AS N2, L3.[Emplid] AS N3, " & _
        "L4.[Emplid] AS N4, L5.[Emplid] AS N5, L6.[Emplid] AS N6, L7.[Emplid] AS N7 FROM ((((([DEU1$] L1 " & _
        "LEFT JOIN [DEU1$] L2 ON L1.[Emplid] = L2.[Supervisor ID]) " & _
        "LEFT JOIN [DEU1$] L3 ON L2.[Emplid] = L3.[Supervisor ID]) " & _
        "LEFT JOIN [DEU1$] L4 ON L3.[Emplid] = L4.[Supervisor ID]) " & _
        "LEFT JOIN [DEU1$] L5 ON L4.[Emplid] = L5.[Supervisor ID]) " & _
        "LEFT JOIN [DEU1$] L6 ON L5.[Emplid] = L6.[Supervisor ID]) " & _
        "LEFT JOIN [DEU1$] L7 ON L6.[Emplid]=L7.[Supervisor ID];"