简体   繁体   中英

VBA access run sql check row count

I'm trying to display a field on a form depending on the results of an sql query. Since I don't know vba in access I'm struggling and don't know where I am going wrong. Help will be greatly appreciated.

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

There are many problems in your code.

First of all Docmd.RumSQL(stringSQL) do not return nothing, and it is not related to your recordset RecordSt.

Also RecordSt.Fields.Count will count the FIELDS of your table and not the number of RECORDS selected.

This is a solution using ADODB. You probably have to add the reference to ADO (you can choose another version if you don't have 6.1) in your Tools->Reference menu from your VBA editor:

在此处输入图片说明

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
If DCount("*", "table1", "id = 2") > 0 Then
   Me.Other.Visible = True
Else
   Me.Other.Visible = False
End if

or even quicker:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM