取消排序或禁止在Access窗体上排序

时间:2018-02-20 13:20:57

标签: vba ms-access access-vba

我有一个带有数据表子表单的Access表单。此数据表子表单显示一个动态创建的记录集(一个数据透视图),并使用一些VBA动态加载该数据透视表,同时允许可变数量的列。

我想禁止对该子表单进行排序,因为一旦子表单被排序,应用程序就会崩溃(不是VBA错误,而是应用程序无法恢复的崩溃)。我已经禁止使用右键菜单,但人们仍然可以使用顶层菜单进行排序,而且我不想禁用主菜单。

无论如何要么禁用排序操作(就像我们可以通过将Form.AllowFilters设置为False来处理过滤器),或者在它运行之前拦截它?

我已尝试在Form_ApplyFilter操作和Form_Filter操作上设置Cancel = True:

Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
    Cancel = True
End Sub
Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)
    Cancel = True
End Sub

然而,这没有帮助。

要重现的相关代码

子窗体包含256个名为Text0到Text255的文本框,它的默认视图是数据表视图。表单和所有文本框都是未绑定的。

子表单上的相关代码:

Public Function LoadRS(myRS As Recordset)
    Dim i As Long
    Dim myTextbox As textbox
    Dim fld As Field
    i = 0
    With myRS
        For Each fld In myRS.Fields
            Set myTextbox = Me.Controls("Text" & i)
            myTextbox.Properties("DatasheetCaption").Value = fld.NAME
            myTextbox.ControlSource = fld.NAME
            myTextbox.ColumnHidden = False
            i = i + 1
        Next fld
    End With
    For i = i To 255
        Set myTextbox = Me.Controls("Text" & i)
        myTextbox.ColumnHidden = True
    Next i
    Set Me.Recordset = myRS
End Function

在主要表格上:

Dim rs As DAO.Recordset
Dim qd As DAO.QueryDef
Set qd = CurrentDb.CreateQueryDef("", "TRANSFORM Max(measurementValue) AS MaxOfValue " & _
    " SELECT measurementValue, measurementCategory, measurementDate " & _
    " From MyTable " & _
    " WHERE ID = ?"  & _
    " GROUP BY measurementCategory" & _
    " PIVOT measurementDate "
qd.Parameters(0) = Me.ID
Set rs = qd.OpenRecordSet()
Me.subformControl.SourceObject = "mySubform"
Me.subformControl.Form.LoadRS rs

1 个答案:

答案 0 :(得分:0)

问题在于,当使用参数化记录集作为源时,Access会手动填写表单的记录源属性和无效的SQL。

我使用的解决方案是设置记录源属性,而不是记录集属性:

Public Function LoadSQL(sqlString As String)
    Dim myRS As DAO.RecordSet
    Set myRS = CurrentDb.OpenRecordset(sqlString)
    Dim i As Long
    Dim myTextbox As textbox
    Dim fld As Field
    i = 0
    With myRS
        For Each fld In myRS.Fields
            Set myTextbox = Me.Controls("Text" & i)
            myTextbox.Properties("DatasheetCaption").Value = fld.NAME
            myTextbox.ControlSource = fld.NAME
            myTextbox.ColumnHidden = False
            i = i + 1
        Next fld
    End With
    For i = i To 255
        Set myTextbox = Me.Controls("Text" & i)
        myTextbox.ColumnHidden = True
    Next i
    Me.RecordSource = sqlString
End Function

有点荒谬的部分是我在问题中提供的代码确实阻止了对表单的排序。但显然不足以阻止Access崩溃。