Option Compare Database
Option Explicit
Private Sub btnCancel_Click()
DoCmd.Close acForm, Me.Name
End Sub
Private Sub btnOK_Click()
Dim flds As String
Dim Vals As String
Dim StrSql As String
If RecordExists(Me.Last_Name, "[Last Name]", "Employees", True) Then
MsgBox "Record already exists"
'Clear Fields
ClearFields
Exit Sub
End If
'validate Fields
If Trim(Me.Last_Name & " ") = "" Then
MsgBox "Must fill in Last Name"
ElseIf Trim(Me.First_Name & " ") = "" Then
MsgBox "Must fill in first name"
ElseIf Trim(Me.City & " ") = "" Then
MsgBox "Must fill in the city"
Else
' All checks passed
'Get field names
flds = insertFields("Last Name", "First Name", "City")
Debug.Print flds
'Get the value part of an insert statement
Vals = insertValues(SqlText(Me.Last_Name), SqlText(Me.First_Name), SqlText(Me.City))
Debug.Print insertValues
StrSql = createInsert("Employees", flds, Vals)
Debug.Print StrSql
CurrentDb.Execute StrSql
MsgBox "Record added"
ClearFields
End If
End Sub
Public Sub ClearFields()
'Edit your fields here
Me.Last_Name = Null
Me.First_Name = Null
Me.City = Null
End Sub
'----------------Do not edit below here
Public Function insertFields(ParamArray varfields() As Variant) As String
Dim fld As Variant
For Each fld In varfields
If insertFields = "" Then
insertFields = "([" & fld & "]"
Else
insertFields = insertFields & ", [" & fld & "]"
End If
Next fld
If Not insertFields = "" Then
insertFields = insertFields & ")"
End If
End Function
Public Function insertValues(ParamArray varValues() As Variant) As String
Dim varValue As Variant
For Each varValue In varValues
If IsNull(varValue) Then varValue = "NULL"
If insertValues = "" Then
insertValues = "(" & varValue
Else
insertValues = insertValues & ", " & varValue
End If
Next varValue
If Not insertValues = "" Then
insertValues = insertValues & ")"
End If
End Function
Public Function SqlText(VarItem As Variant) As String
If Not IsNull(VarItem) Then
VarItem = Replace(VarItem, "'", "''")
SqlText = "'" & VarItem & "'"
End If
End Function
Public Function SQLDate(varDate As Variant) As String
If IsDate(varDate) Then
If DateValue(varDate) = varDate Then
SQLDate = Format$(varDate, "\#mm\/dd\/yyyy\#")
Else
SQLDate = Format$(varDate, "\#mm\/dd\/yyyy hh\:nn\:ss\#")
End If
End If
End Function
Public Function createInsert(tableName As String, flds As String, Vals As String) As String
createInsert = "INSERT INTO " & tableName & " " & flds & " VALUES " & Vals
End Function
Public Function RecordExists(Value As Variant, fieldName As String, tableName As String, Optional IsTextField As Boolean = False) As Boolean
'Valtype is either Date, Numeric, or String
Dim recCount As Integer
If IsTextField Then Value = "'" & Value & "'"
recCount = DCount(fieldName, tableName, fieldName & " = " & Value)
MsgBox recCount
RecordExists = (recCount > 0)
End Function
[/code}