我有查询表的VBA代码。 MS Access中的Query视图返回正确的结果,但vba返回不同的结果。
表名为tbl_ADMIN_CLASS_INFO
Client_ID | POLICY_GROUP
12345a | 1
12345a | 2
12345a | 2
12345a | 2
12345a | 2
表中的列定义:
CLIENT_ID = Text
POLICY_GROUP = Number
VBA
Public Sub NextPageControl()
Dim dbs As Database
Dim rst As Recordset
Dim CurrentTableName As String
Dim CurrentFormName As String
Dim NextPageSQL As String
Dim CurrentPage As Form
Dim LastRecord As Integer
Dim Nextpage As Integer
Dim TestPolicy As Long
Dim TestClient As String
TestPolicy = Forms!frm_ADMIN_CLASS_INFO.POLICY_GROUP 'Stepping Through Code shows 12345a
TestClient = Forms!frm_ADMIN_CLASS_INFO.CLIENT_ID 'Stepping Through Code shows 2
CurrentTableName = Screen.ActiveForm.RecordSource
CurrentFormName = Screen.ActiveForm.Name
Set CurrentPage = Screen.ActiveForm
Set dbs = CurrentDb
NextPageSQL = "SELECT * FROM " & CurrentTableName & " WHERE ((POLICY_GROUP = " & TestPolicy & ") AND (CLIENT_ID = '" & TestClient & "'))"
Debug.Print NextPageSQL
Set rst = CurrentDb.OpenRecordset(NextPageSQL, dbOpenDynaset)
MsgBox rst.RecordCount
...More Stuff
问题是当rst.RecordCount
返回4时,此VBA返回5 ....
答案 0 :(得分:0)
首先,以下说明并非最佳,因为如果您的表单的记录源是SQL查询而不是表格,它可能会欺骗您:
CurrentTableName = Screen.ActiveForm.RecordSource
因此,请确保此指令重新生成正确的表名。
其次:使用recordset.recordcount可能不会返回预期的结果,具体取决于您的游标类型和数据源。来自微软:
Recordset对象的游标类型是否影响数量 记录可以确定。 RecordCount属性将返回-1 只向前游标;静态或键集游标的实际计数; 并且-1或动态游标的实际计数,具体取决于 数据源。
因此,为了确保您始终返回正确数量的记录,请执行以下操作:
rst.movelast
在执行记录计数之前
在更正后,您的代码应该可以正常工作。