我正在尝试在VBA中编写一个SQL语句来连接名字和

时间:2016-11-15 19:32:25

标签: sql vba access

我收到错误。

SELECT [FirstName] & " " & [LastName] AS FullName, TblMembers.Position
FROM TblMembers
WHERE (((TblMembers.Position)="Lt #1"));

这是原作......

SQL = "SELECT [FirstName] & " " & [LastName] AS FullName, TblMembers.Position
       FROM TblMembers
       WHERE (((TblMembers.Position)="Lt #1"));"

我将名称导出为ex​​cel文件,并且有多个文件,不想对每个文件进行查询,因此想要在打开时提取数据。

以下是我的完整代码,更正如下。

Private Sub Cmdtestopen_Click()


On Error GoTo SubError

    Dim xlApp As Excel.Application
    Dim xlBook As Excel.Workbook
    Dim xlSheet As Excel.Worksheet
    Dim SQL As String
    Dim rs1 As DAO.Recordset


    SQL = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.Position " & _
    " FROM TblMembers " & _
    " WHERE TblMembers.Position='Lt #1' "


    Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)


    If rs1.RecordCount = 0 Then
        MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
        GoTo SubExit
    End If


    Set xlApp = Excel.Application

    xlApp.Visible = False
    Set xlBook = xlApp.Workbooks.Add
    Set xlSheet = xlBook.Worksheets(1)

    With xlSheet
        .Name = "Discount"
        .Cells.Font.Name = "Calibri"
        .Cells.Font.Size = 11


        Do While Not rs1.EOF

            .Range("A1").Value = Nz(rs1!FullName, "")


            rs1.MoveNext

        Loop


    End With


SubExit:
On Error Resume Next

    DoCmd.Hourglass False
    xlApp.Visible = True
    rs1.Close
    Set rs1 = Nothing

    Exit Sub

SubError:
    MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
        "An error occurred"
    GoTo SubExit


End Sub

1 个答案:

答案 0 :(得分:2)

双引号分隔String字面值。要在里面添加双引号 String字面值,您需要"转义"他们;在VBA中,这样做的方法是将双引号加倍:

SQL = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.Position " & _
      " FROM TblMembers " & _
      " WHERE TblMembers.Position='Lt #1' "