如何通过VBA对Access DB表进行排序,使用导航窗格打开时按顺序显示

时间:2016-02-14 13:28:59

标签: vba ms-access access-vba ms-access-2013

作为一些插入的结束,通过VBA脚本,我一直在ACCESS表中。我要求按字段订购表格。因此,第三个人将通过ACCESS导航窗格打开它,它将按指定的顺序显示。 编辑:我也需要这个表可由第三人写。

我可以考虑创建一个新表,使用SQL语句对其进行排序。但这似乎是一个非常难看的选择。

有没有办法使用DAO对象或其他VBA方法对其进行归档?

1 个答案:

答案 0 :(得分:1)

对表进行排序的查询是最干净的解决方案。

如果您不想为此创建额外的对象,可以使用DAO属性设置表排序,如下所示:

Sub DoIt()

    Call TableSetSort("myTable", "myField")

End Sub

' Set a table to be sorted by <sFieldname>
Public Sub TableSetSort(sTable As String, sFieldname As String)

    Dim DB As Database
    Dim tdf As TableDef
    Dim prop As DAO.Property

    Set DB = CurrentDb
    Set tdf = DB.TableDefs(sTable)

    ' Set field to order by
    Call TableAddProperty(tdf, "OrderBy", dbText, sFieldname)
    ' These two may be true by default, but better safe than sorry
    Call TableAddProperty(tdf, "OrderByOn", dbBoolean, True)
    Call TableAddProperty(tdf, "OrderByOnLoad", dbBoolean, True)

    ' if you want to debug
    For Each prop In tdf.Properties
        Debug.Print prop.Name, prop.Value
    Next prop

End Sub

' Set or add a property in a TableDef
Public Sub TableAddProperty(tdf As DAO.TableDef, sName As String, iType As DAO.DataTypeEnum, vValue As Variant)

    Dim prop As DAO.Property

    ' Try to set the property value, this will fail with Runtime Error 3270 if the property doesn't exist
    On Error Resume Next
    tdf.Properties(sName) = vValue

    If Err.Number = 3270 Then
        ' Property doesn't exist yet - create and append it
        On Error GoTo 0
        Set prop = tdf.CreateProperty(sName, iType, vValue)
        tdf.Properties.Append prop
    End If
    ' Note: error handling here is quite minimal!

End Sub