问题
I have a form in access, where I want to make 3 fields (FYear
, cboPeriodicity
, cboPeriod
) compulsory if another field cboCompliance
is filled in by user.
I have tried the below code, where I am canceling save, if any of these fields are Empty. And also giving error message through msgBox
Private Sub Form_BeforeUpdate(Cancel As Integer)
On Error GoTo Form_BeforeUpdate_Err
'Audit Data Values Set
Me.LastModifiedBy.Value = [TempVars]![currentUserID]
Me.LastModifiedTime.Value = Now()
'If Compliance value is filled, make other vaules compulsory
If IsNull(Me.cboCompliance.Value) Or Len(Me.cboCompliance.Value) <= 0 Then
'DO nothing
Else
Dim txtFiledisEmpty As String
Dim wantToCancel As Boolean
'Finiancial year ending
If IsNull(Me.FYear.Value) Then
wantToCancel = True
txtFiledisEmpty = "If Compliance is selected, FY ENDING cannot be blank" & char(10)
Me.FYear.SetFocus
End If
'Periodicity
If IsNull(Me.cboPeriodicity.Value) Then
wantToCancel = True
txtFiledisEmpty = "If Compliance is selected, PERIODICITY cannot be blank" & char(10)
Me.cboPeriodicity.SetFocus
End If
'Period
If IsNull(Me.cboPeriod.Value) Then
wantToCancel = True
txtFiledisEmpty = "If Compliance is selected, PERIOD cannot be blank"
Me.cboPeriod.SetFocus
End If
MsgBox "Error"
Cancel = wantToCancel
End If
'Error Handling
Form_BeforeUpdate_Exit:
Exit Sub
Form_BeforeUpdate_Err:
MsgBox Error$
Resume Form_BeforeUpdate_Exit
End Sub
I am unable to find (after an about hr of debugging), where the problem is.
Thanks in advance.
回答1:
There was a silly mistake in my code.
Char
should have been chr
The code was modified a little, to better messages.
Private Sub Form_BeforeUpdate(Cancel As Integer)
On Error GoTo Form_BeforeUpdate_Err
'If Compliance value is filled, make other vaules compulsory
If IsNull(Me.cboCompliance.Value) Or Len(Me.cboCompliance.Value) <= 0 Then
'DO nothing
Else
Dim txtFiledisEmpty As String
txtFiledisEmpty = "If Compliance is selected, " & Chr(10)
Dim wantToCancel As Boolean
wantToCancel = False
'Period
If IsNull(Me.cboPeriod.Value) Then
wantToCancel = True
txtFiledisEmpty = txtFiledisEmpty & " > PERIOD cannot be blank" & Chr(10)
Me.cboPeriod.SetFocus
End If
'Periodicity
If IsNull(Me.cboPeriodicity.Value) Then
wantToCancel = True
txtFiledisEmpty = txtFiledisEmpty & " > PERIODICITY cannot be blank" & Chr(10)
Me.cboPeriodicity.SetFocus
End If
'Finiancial year ending
If IsNull(Me.FYear.Value) Then
wantToCancel = True
txtFiledisEmpty = txtFiledisEmpty & " > FY ENDING cannot be blank" & Chr(10)
Me.FYear.SetFocus
End If
If wantToCancel Then
MsgBox txtFiledisEmpty
End If
Cancel = wantToCancel
End If
'Error Handling
Form_BeforeUpdate_Exit:
Exit Sub
Form_BeforeUpdate_Err:
MsgBox Error$
Resume Form_BeforeUpdate_Exit
End Sub
来源:https://stackoverflow.com/questions/31982107/make-fileds-compulsory-if-a-particular-filed-is-filled-in-access-form