VBA访问运行sql检查行计数

时间:2014-07-31 14:08:17

标签: sql vba

我试图在表单上显示一个字段,具体取决于sql查询的结果。由于我不知道vba在访问中我挣扎并且不知道我哪里出错了。非常感谢帮助。

Dim RecordSt As Recordset
Dim dBase As Database
Dim stringSQL As String

Set dBase = CurrentDb()

stringSQL = "SELECT * FROM Table1 WHERE ID = 2"

DoCmd.RunSQL (stringSQL)

If RecordSt.Fields.Count > 0 Then
Me.Other.Visible = True
Else
Me.Other.Visible = False
End If

2 个答案:

答案 0 :(得分:0)

您的代码中存在许多问题。

首先是Docmd.RumSQL(stringSQL) 不要返回任何内容,它与您的记录集RecordSt无关。

此外,RecordSt.Fields.Count将统计您桌子的FIELDS,而不是所选RECORDS的数量。

这是使用ADODB的解决方案。您可能需要在VBA编辑器的Tools-> Reference菜单中添加对ADO的引用(如果您没有6.1,则可以选择其他版本):

enter image description here

Dim rst As new ADODB.Recordset
Dim stringSQL As String

stringSQL = "SELECT * FROM Table1 WHERE ID = 2"

rst.Open SQL, CurrentProject.AccessConnection
If rst.RecordCount > 0 Then
    Me.Other.Visible = True
Else
    Me.Other.Visible = False
End If

答案 1 :(得分:0)

If DCount("*", "table1", "id = 2") > 0 Then
   Me.Other.Visible = True
Else
   Me.Other.Visible = False
End if

甚至更快:

Me.Other.Visible = (DCount("*", "table1", "id = 2") > 0)