ACC: How to Count Values in Record or Recordset Across FieldsLast reviewed: August 28, 1997Article ID: Q142227 |
The information in this article applies to:
SUMMARYAdvanced: Requires expert coding, interoperability, and multi-user skills. This article defines a sample user-defined Visual Basic for Applications routine that you can use to count the occurrence of a specific field value in a record or recordset. This article assumes that you are familiar with Visual Basic for Applications and with creating Microsoft Access applications using the programming tools provided with Microsoft Access. For more information about Visual Basic for Applications, please refer to your version of the "Building Applications with Microsoft Access" manual. NOTE: Visual Basic for Applications is called Access Basic in Microsoft Access version 2.0. For more information about Access Basic, please refer to the "Building Applications" manual.
MORE INFORMATIONThe following function is designed for text fields, but it can be modified to work with any data type and assumes that all fields are of the same data type. This function is designed to work on a single table or query; it accepts two arguments:
ExamplesTo create the function, follow these steps:
If you want to search all fields in only one record, use the following sample code for your version of Microsoft Access. This example searches all fields in the first record only. Microsoft Access Versions 7.0 and 97:
Function CountOccurrenceRecord(strval As String, sourcename As _ String) Dim db As DATABASE, rs As Recordset, Strval_Count As Integer Dim I As Integer Set db = CurrentDb Set rs = db.OpenRecordset(sourcename, DB_OPEN_DYNASET) rs.MoveFirst Strval_Count = 0 For I = 0 To rs.Fields.Count - 2 If TypeName(rs.Fields(I).Value) <> "Byte()" Then If rs.Fields(I).Value = strval Then Strval_Count = Strval_Count + 1 End If End If Next I MsgBox "Count of " & strval & " found = " & Strval_Count CountOccurrenceRecord = Strval_Count End FunctionMicrosoft Access Version 2.0: NOTE: In the following sample code, an underscore (_) at the end of a line is used as a line-continuation character. Remove the underscore from the end of the line when re-creating this code in Access Basic.
Function CountOccurrenceRecord (strval As String, sourcename As _ String) Dim db As Database, rs As Recordset, Strval_Count As Integer Set db = dbengine(0)(0) Set rs = db.OpenRecordset(sourcename, DB_OPEN_DYNASET) rs.MoveFirst Strval_Count = 0 For i = 0 To rs.fields.Count - 1 If rs.fields(i) = strval Then Strval_Count = Strval_Count + 1 End If Next i MsgBox "Count of " & strval & " found = " & Strval_Count CountOccurrenceRecord = Strval_Count End Function |
Additional query words: how to
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |