简体   繁体   English

VBA 和访问表单过滤器

[英]VBA and Access Form Filter

I have this form in access, the purpose of it is to work as a front end of a table which can be edited through this form.我有这个表格可以访问,它的目的是作为表格的前端,可以通过这个表格进行编辑。 Initially when it loads I display in the form data from a recordset with the following query:最初,当它加载时,我使用以下查询在记录集中显示表单数据:

SELECT * FROM DATA

I want to be able to filter the data on the recordset once the form is open.我希望能够在表单打开后过滤记录集上的数据。 I tried the following VBA code to accomplish this:我尝试了以下 VBA 代码来完成此操作:

Private Sub Filter_Click()
    If (IsNull(Me.Find_Field) Or Me.Find_Field = "") Then
        rs.Close
        Set rs = db.OpenRecordset("Select * from DATA ORDER BY ID)
        rs.MoveFirst
        LoadData (True)
        Exit Sub
    End If

    Set rs = db.OpenRecordset("Select * from DATA WHERE ID = " & Me.Find_Field)


    rs.MoveFirst
    LoadData (True) ' Function that loads the data into the form
Exit Sub

As you all can see, I reload the recordset with a new filtered query.如您所见,我使用新的过滤查询重新加载记录集。 Up to this point it works, the problems begin when I try to modify a record.到目前为止,它可以工作,当我尝试修改记录时问题就开始了。

Originally, when the form loads the recordset data, I am able to edit the data and the edited data would show in the table (which is what I want).最初,当表单加载记录集数据时,我能够编辑数据并且编辑后的数据将显示在表格中(这是我想要的)。 But after I apply my filter, my code gives me the Run-Time error '3027': Cannot Update.但是在我应用过滤器后,我的代码给了我运行时错误“3027”:无法更新。 Databse or object is read-only.数据库或 object 是只读的。

I am pretty much using the same code over and over to reload data from the table and it never gave me a problem until I 'overwrote' the source of the recordset.我几乎一遍又一遍地使用相同的代码从表中重新加载数据,并且在我“覆盖”记录集的源之前它从来没有给我带来问题。 Any idea how can I resolve this issue?知道如何解决这个问题吗? Thanks谢谢

I would prefer to use a standard Access bound form because it's simpler than what you appear to be doing.我更喜欢使用标准的 Access 绑定表单,因为它比您看起来正在做的更简单。

I can change the form's RecordSource from the click event of my cmdApplyFilter button.我可以从我的cmdApplyFilter按钮的单击事件中更改表单的 RecordSource。

Private Sub cmdApplyFilter_Click()
    Dim strSql As String
    If Len(Me.txtFind_Field & vbNullString) > 0 Then
        strSql = "SELECT * FROM tblFoo WHERE id = " & _
            Me.txtFind_Field & " ORDER BY id;"
        Me.RecordSource = strSql
    End If
End Sub

If you're concerned someone might save the form with the filtered RecordSource, you can make the form always open with the unfiltered version.如果您担心有人可能会使用过滤的 RecordSource 保存表单,您可以使表单始终使用未过滤的版本打开。

Private Sub Form_Open(Cancel As Integer)
    Dim strSql As String
    strSql = "SELECT * FROM tblFoo ORDER BY id;"
    Me.RecordSource = strSql
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM