Tom,
This creates a temp query "TempZXZ" each time it is called. Should be helpful.
Code:
Option Compare Database
Option Explicit
' ----------------------------------------------------------------
' Procedure Name: whichFldsHaveValues
' Purpose: To identify which short text fields in table/recordset have values
' and create and run a tempquery to count the total records with values in these fields
' Procedure Kind: Function
' Procedure Access: Public
' Parameter sTableName (String): table whose fields to check
' Author: Jack
' Date: 02-Jul-21
' ----------------------------------------------------------------
Function whichFldsHaveValues(sTableName As String)
10 On Error Resume Next
20 DoCmd.DeleteObject acQuery, "TempZXZ" 'Delete the temp query if it exists
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim tmpQDef As DAO.QueryDef
Dim FinalSQL As String
Dim fld As DAO.Field
Dim sresult As String
Dim QString As String
Dim i As Integer
Dim FieldsSQL
Dim createSQL1 As String 'start sql
Dim createSQL2 As String 'end sql
30 Set db = CurrentDb
40 Set rs = db.OpenRecordset(sTableName)
50 For Each fld In rs.Fields
60 If fld.Value > " " Then
70 sresult = sresult & fld.Name & " "
80 End If
90 Next
100 sresult = Mid(sresult, 1, Len(sresult) - 1)
110 FieldsSQL = Split(sresult, " ")
'Create the query sql
120 createSQL1 = "Select "
130 createSQL2 = " from " & sTableName
140 For i = LBound(FieldsSQL) To UBound(FieldsSQL)
150 QString = QString & "Count (" & FieldsSQL(i) & ") as Cnt" & FieldsSQL(i) & ", "
160 Next i
170 FinalSQL = createSQL1 & Mid(QString, 1, Len(QString) - 2) & createSQL2 & ";"
180 Set tmpQDef = db.CreateQueryDef("TempZXZ", _
FinalSQL)
190 DoCmd.OpenQuery "TempZXZ", acViewNormal 'query result in query window
End Function
This is how the routine is called from immediate window
?whichFldsHaveValues("tbl_example")
Result: