使用ORDER BY Access VBA

时间:2016-05-15 18:38:58

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

我正在尝试创建一个根据表和某个表单的当前Orderby属性排序的记录集。由于Orderby属性将在用户更改时更改,因此我创建了一个函数,该函数仅在Orderby属性中获取第一个字段(可以使用多于1个字段对其进行排序),并使用它创建有序记录集。字段名称从getField函数给出的是正确的,但我假设"Set rsAll = ..."的语法不正确,我认为这导致代码停止。

以有序方式创建Recordset。

Dim rsAll As DAO.Recordset
If Len(Forms("All Patient Sub").OrderBy) > 0 Then
Set rsAll = CurrentDb.OpenRecordset("SELECT * FROM [All Patient Info] ORDER BY " & getField(Forms("All Patient Sub").OrderBy)) 'code stops here
Else
Set rsAll = CurrentDb.OpenRecordset("All Patient Info")
End If

从属于表单的Orderby属性中获取字段名称的函数

Public Function getField(ByVal sorter As String) As String
Debug.Print "Started"
'i = 21 hence [All Patient Info].[ is skipped and starts from the field's name
    For i = 21 To Len(sorter)
        If Mid(sorter, i, 1) = "]" Then
            getField = Mid(sorter, 21, i - 21)
            Exit For
        End If
    Next i
Debug.Print getField
End Function

1 个答案:

答案 0 :(得分:0)

我并不真正关注你的代码;但是既然你只想要orderBy中的第一列,那么:

此功能需要放在一个模块中:

'this returns either " ORDER BY [column name]" or an empty string, if there is no column name to order by
public function OrderByClause(propValue as string) as string
    dim cols as string()

    if propValue = "" then
        OrderByClause = ""
    else
        cols = split(propValue, ",")
        dim junk as string: junk = cols(0)
        if instr(junk, ".") > 0 then
            junk = mid(junk, instr(junk, ".") + 1)
        end if
        OrderByClause = " ORDER BY " & junk
    end if
end function

然后以你的形式:

Dim rsAll As DAO.Recordset
Dim src as string
src = OrderByClause(Forms("All Patient Sub").OrderBy & "")
src = "SELECT * FROM [All Patient Info]" & src

Set rsAll = CurrentDb.OpenRecordset(src)

由于OrderByClause函数始终返回一个值,因此无论属性设置为什么,您都可以在表单中调用它;调用使用...& “”如果属性实际上为null,则防止出现错误。