如何在通过 VBA 打开时对 Access DB 表进行排序以按正确顺序显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23526776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:01:59  来源:igfitidea点击:

How to sort an Access DB Table to show in right order when opening via VBA?

vbams-accessaccess-vbams-access-2010

提问by tarheel

I already have a VBA script that edits this, that, and the other and even opens the table at the end of the script. The only problem is that I want the data I am viewing to be sorted by columnA, and then by columnB.

我已经有一个 VBA 脚本可以编辑这个、那个和另一个,甚至在脚本的末尾打开表格。唯一的问题是我希望我查看的数据按列 A 排序,然后按列 B 排序。

How do I do that via VBA in Access 2010?

我如何通过 Access 2010 中的 VBA 做到这一点?

回答by Linger

If you just want to see the record set then you could do something like the following:

如果您只想查看记录集,则可以执行以下操作:

Dim qdef As Dao.QueryDef
Set qdef = CurrentDb.CreateQueryDef("MyQuery", "SELECT * " & _
                                               "FROM TableName " & _
                                               "ORDER BY columnA, columnB")
DoCmd.OpenQuery "MyQuery"

Then once you are done doing whatever it is you want to do with it you could execute the following to remove the query:

然后一旦你完成了你想做的任何事情,你就可以执行以下操作来删除查询:

On Error Resume Next
DoCmd.DeleteObject acQuery, "MyQuery"

Or you could do the following:

或者您可以执行以下操作:

Dim RSData as DAO.Recordset
Set RSData = CurrentDB.OpenRecordSet("SELECT * " & _
                                     "FROM TableName " & _
                                     "ORDER BY columnA, columnB")
If (RSData.RecordCount > 0) Then
  RSData.MoveFirst
  Do While RSData.EOF <> True
    'HERE YOU CAN WORK WITH EACH FIELD OF THE RECORD INDIVIDUALLY USING 
    RSData.Fields("columnA").value

    RSData.MoveNext
  Loop
End If

Then once you are done doing whatever it is you want to do with it you could execute the following:

然后一旦你完成了你想做的任何事情,你可以执行以下操作:

RSData.Close
Set RSData = Nothing