There is a field that contains special character when it is passed to a function, it doesn't acknowledge that the field exist in the table. When I remove the special chars, it passes the field and performs a delete on the field.
The field name is [Sales Order Date/Time Created] from table SO_Data.
Thank you in advance for your assistance.
The sub that calls the functions:
the functions:
The field name is [Sales Order Date/Time Created] from table SO_Data.
Thank you in advance for your assistance.
The sub that calls the functions:
Code:
If ifFieldExists("[Sales Order Date/Time Created]", "SO_Data") Then
'Call the Function
DeleteField "SO_Data", "[Sales Order Date/Time Created]"
Else
MsgBox "Field Does not exist", vbInformation, "Field - [Sales Order Date/Time Created], Table: SO_Data"
End If
Code:
Option Compare Database
Option Explicit
Function ifFieldExists(FieldName As String, TableName As String) As Boolean
Dim rs As Recordset, Db As Database ' DAO Vars
'References: Microsoft Access 11.0 Object Library, Microsoft DAO 3.6 Object Library
'Set references by Clicking Tools and Then References in the Code View window
'Checks if Field exists.
'USAGE: ifFieldExists "FIELDNAME", "TABLENAME"
On Error GoTo NoField 'If there is no Field capture the error.
Set Db = CurrentDb()
'If Field is there open it
Set rs = Db.OpenRecordset("Select " & FieldName & " from " & TableName & ";")
ifFieldExists = True
rs.Close
ExitHere:
Set rs = Nothing
Db.Close
Set Db = Nothing
Exit Function
NoField:
'If Field is not present set function to false
ifFieldExists = False
With Err
MsgBox "Error " & .Number & vbCrLf & .Description, _
vbOKOnly Or vbCritical, "ifFieldExists"
End With
Resume ExitHere
Exit Function
End Function
Function DeleteField(tblName As String, strField As String) As Boolean
Dim Db As DAO.Database
Dim tdf As DAO.TableDef
On Error GoTo errhandler
' References: Microsoft Access 11.0 Object Library, Microsoft DAO 3.6 Object Library
' Set references by Clicking Tools and Then References in the Code View window
' Returns True on Success, False otherwise.
' Accepts
' tblName: Name of Table that the Field is located
' strField: Name of Field to delete
' Deletes Field strField in Table tblName.
' USAGE: DeleteField "tblName", "strField"
Set Db = CurrentDb()
'Set tblName to your table mine is 1A
Set tdf = Db.TableDefs(tblName)
'Execute the delete
tdf.Fields.Delete (strField)
DeleteField = True
MsgBox "Delete Field " & strField & " Complete."
Db.Close
ExitHere:
Set Db = Nothing
Set tdf = Nothing
Exit Function
errhandler: 'There is an error return as False
DeleteField = False
With Err
MsgBox "Error " & .Number & vbCrLf & .Description, _
vbOKOnly Or vbCritical, "deletefield"
End With
Resume ExitHere
End Function
Comment