Field Exists check in MS Access VBA

We had a scenario of checking whether the column/field is available in Access table or not. If the specified column is available, then it is fine and go ahead and perform necessary operations. If specified field is not available need to add column. So we had to develop a function to check the specified field is available or not.
Private Sub check()

Set db = CurrentDb

If ifFieldExists("ID", "Table1") Then
MsgBox "ID field available"
Else
MsgBox "ID field is not available"
End If

End Sub
________________________________________________________________________________

Public Function ifFieldExists(fldname As String, tableName As String) As Boolean
Dim rs As Recordset, db As Database 'Sub DAO Vars
On Error GoTo fs

'This checks if a Table is there and reports True or False.

Set db = CurrentDb()

'If Table is there open it
Set rs = db.OpenRecordset("Select " & fldname & " from " & tableName & ";")

ifFieldExists = True
rs.Close
db.Close

Exit Function

fs:
'If table is not there close out and set function to false
Set rs = Nothing
db.Close
Set db = Nothing

     ifFieldExists = False
  Exit Function
End Function

No comments:

Post a Comment