@dovid
Option Compare Database
Sub AddNewField()
' ==============================================
' Example code for AddFieldToTable()
' ----------------------------------------------
' Prompts the user for a field name and then
' adds a text field with that name to the
' Customers table in the current database.
' ==============================================
Dim bOK As Boolean
Dim strName As String
Const MyFieldLength = 20
strName = InputBox("What is the new field's name?")
If strName <> "" Then
bOK = AddFieldToTable("", "Customers", strName, dbText, MyFieldLength)
If Not bOK Then
MsgBox "Error: Unable to add new field."
End If
End If
End Sub
Function AddFieldToTable(strDatabase As String, strTable As String, strField As String, intDataType As Integer, intLength As Integer) As Boolean
' Comments : Adds a field to a table in any database
' Parameters: strDatabase - path and name of the database or "" (blank string) for the current database
' strTable - name of the table
' strField - name of the field to add
' intDataType - type of field dbText, dbMemo, etc.
' intLength - length of field
' Returns : True - field was added, False - field was not added
'
Dim db As Database
Dim tdf As TableDef
Dim fld As Field
On Error GoTo err_AddFieldToTable
If strDatabase = "" Then
Set db = CurrentDb()
Else
Set db = DBEngine.Workspaces(0).OpenDatabase(strDatabase)
End If
Set tdf = db.TableDefs(strTable)
If intDataType = dbText Then
Set fld = tdf.CreateField(strField, intDataType, intLength)
Else
Set fld = tdf.CreateField(strField, intDataType)
End If
tdf.Fields.Append fld
AddFieldToTable = True
exit_AddFieldToTable:
db.Close
Exit Function
err_AddFieldToTable:
AddFieldToTable = False
Resume exit_AddFieldToTable
End Function