重新查询子表单有时只能工作

时间:2018-05-23 19:13:57

标签: vba ms-access access-vba

我正在尝试重新查询显示客户详细信息的子表单。

我确信我的sql工作,因为子窗体在不受主窗体影响的情况下工作正常。

Private Sub btnSearch_Click()
    Dim sql As String

    sql = "SELECT tblCustomer.[Job ID], tblCustomer.[Customer Name], tblCustomer.[Street Name], tblCustomer.Area, tblAppointments.[Appointment Date] " _
    & "FROM tblCustomer " _
    & "LEFT JOIN tblAppointments ON tblCustomer.[Job ID] = tblAppointments.[Job Number].Value " _
    & "WHERE [Customer Name] LIKE '*" & Me.txtKeywords & "*'" _
    & "OR [Job ID] LIKE '*" & Me.txtKeywords & "*'" _
    & "OR [Street Name] LIKE '*" & Me.txtKeywords & "*'" _
    & "OR [Area] LIKE '*" & Me.txtKeywords & "*'" _
    & "OR [Appointment Date] LIKE '*" & Me.txtKeywords & "*'" _
    & "ORDER BY tblAppointments.[Appointment Date];"

    Me.subCustomerList.Form.RecordSource = sql
    Me.subCustomerList.Form.Requery
End Sub

调试器在以下行显示错误:

Me.subCustomerList.Form.RecordSource = sql

我也收到错误消息

  

对象或类不支持事件集

2 个答案:

答案 0 :(得分:2)

在您的情况下,出于多种原因考虑使用存储的查询进行参数化:

  1. 如果使用GUI查询设计器,则有助于避免语法问题,例如Access,因为Access不允许您保存带语法错误的查询;
  2. 比串联SQL字符串更好的可维护性,它需要单/双引号封装,并且您从代码中抽象数据;
  3. Access引擎将存储的查询编译为最佳执行计划,因此比称为SQL字符串的VBA更有效(即使用JOIN上的索引)。
  4. SQL (另存为查询对象,其参数将在VBA中按名称引用)

    PARAMETERS txtKeywordsParam TEXT(255);
    SELECT c.[Job ID], c.[Customer Name], c.[Street Name], c.Area, a.[Appointment Date]
    FROM tblCustomer c
    LEFT JOIN tblAppointments a ON c.[Job ID] = a.[Job Number]
    WHERE c.[Customer Name] LIKE txtKeywordsParam 
      OR c.[Job ID] LIKE txtKeywordsParam 
      OR c.[Street Name] LIKE txtKeywordsParam 
      OR c.[Area] LIKE txtKeywordsParam 
      OR a.[Appointment Date] LIKE txtKeywordsParam 
    ORDER BY a.[Appointment Date];
    

    <强> VBA

    Private Sub btnSearch_Click()
        Dim qdef As QueryDef
        Dim rst As Recordset
    
        ' OPEN QUERY AND BIND PARAM
        Set qdef = CurrentDb.QueryDefs("mySavedParamQuery")
        qdef!txtKeywordsParam = "*" & Me.txtKeyword & "*"
    
        ' ASSIGN QUERY RESULT TO RECORDSET
        Set rst = qdef.OpenRecordset()    
    
        ' APPLY RECORDSET TO FORM 
        Set Me.subCustomerList.Form.Recordset = rst    
        Set qdef = Nothing    
    End Sub
    

答案 1 :(得分:0)

我创建了一个新的子窗体并复制了一个不起作用的子窗体,一切似乎运行良好。