This question is an offshoot of this question here. Using an loop to loop through the recordset based on the Master table, I was able to get all the records returned by my inline Sql statement to show. However, when I actually put the validation code in the loop, valid employees are being reported as invalid and vice versa.
Public Function validEmployee(EmpID as String)
Dim Dbs As DAO.database
Dim rs As DAO.recordset
Dim sqlString as String
set dbs = CurrentDb
sqlString = "SELECT [EmployeeID] FROM [MASTER] WHERE [EmployeeStatus] = 'Terminated'"
set rs = dbs.OpenRecordset(sqlString)
rs.MoveLast
rs.MoveFirst // obtain accurate count of records in recordset
If Not (rs.BOF and rs.EOF) Then // Verify recordset is not empty
Do Until rs.EOF
If InStr(1, rs.fields("EmployeeID"), EmpID, vbTextCompare) = 0
validEmployee = "Valid employee"
Else
validEmployee = "Employee" & EmpID & "is invalid"
Exit Do
End If
Loop
rs.moveNext
End If
Some of the steps I have tried include:
- checking for leading or trailing spaces in field names
- validating the values of EmpID and rs.fields("EmployeeID") via debug.print
- Checking for syntax errors both in SQL and in VBA
- Quotation / escaping of string literals in SQL statement
I feel the problem could be in the way I wrote my InStr() comparison. Comparison using just a single record without the loop works fine.
MoveNextneeds to be before theLoop- Tim Williams//comments in VBA? - cha