T Kirtley said:
How can I check to see if a table has a specific column name? If the
column
exists I want to drop the column, otherwise I want to leave it alone.
I thought that the column names would be in the MSysObjects table, but I
cannot find it. Can anyone poitn me in the right direction?
Thanks,
TK
Obviously writing your own subs and functions, you can structure your code
as you please, but here is one possibility... Paste this into a new module:
Option Compare Database
Option Explicit
Public Sub DeleteColumnIfExists(strTable As String, strColumn As String)
On Error GoTo Err_Handler
If ColumnExists(strTable, strColumn) Then
If Not DeleteColumn(strTable, strColumn) Then
' Leave function to display error message
End If
End If
Exit_Handler:
Exit Sub
Err_Handler:
MsgBox Err.Description, vbExclamation, "Error No: " & Err.Number
Resume Exit_Handler
End Sub
Public Function ColumnExists(strTable As String, strColumn As String) As
Boolean
On Error GoTo Err_Handler
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set dbs = CurrentDb
Set tdf = dbs.TableDefs(strTable)
Set fld = tdf.Fields(strColumn)
ColumnExists = True
Exit_Handler:
On Error Resume Next
Set fld = Nothing
Set tdf = Nothing
Set dbs = Nothing
Exit Function
Err_Handler:
Select Case Err.Number
Case 3265
' No Error message - just return false
Case Else
MsgBox Err.Description, vbExclamation, "Error No: " & Err.Number
End Select
Resume Exit_Handler
End Function
Public Function DeleteColumn(strTable As String, strColumn As String) As
Boolean
On Error GoTo Err_Handler
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set dbs = CurrentDb
Set tdf = dbs.TableDefs(strTable)
Set fld = tdf.Fields(strColumn)
tdf.Fields.Delete fld.Name
DeleteColumn = True
Exit_Handler:
On Error Resume Next
Set fld = Nothing
Set tdf = Nothing
Set dbs = Nothing
Exit Function
Err_Handler:
MsgBox Err.Description, vbExclamation, "Error No: " & Err.Number
Resume Exit_Handler
End Function