vbams-access

Trying to use VBA in Access to force string to be a specific Length


I am very new to VBA. So I'm not sure where to even start with solving this. I have a phone number entry and to avoid future errors I would like to force the data entered be blank/null or to have a length of either 7 or 10 and the user cannot move off the field if not the correct length.

I tried using IF statements to confirm length and have been able to get a message box to pop up when conditions aren't met but I don't know how to keep focus there until the correct length is entered.

Private Sub InspWkPhone_AfterUpdate()
    Me.Refresh
    If Len(Me.InspWkPhone) <> 7 Then
        If Len(Me.InspWkPhone) <> 10 Then
            MsgBox (" Check Phone # MISSING digits! ")
        End If
    End If
End Sub

Ultimately there are several types of numerical data being entered before and after the phone number. I am trying to avoid a zip code or unit price being put in the wrong location.


Solution

  • If you use a Select Case approach, you can consolidate the acceptance conditions into one line. I prefer that to the nested If ... Then blocks. See what you think.

    I discarded Me.Refresh because I don't see a benefit here.

    You can use your control's SetFocus method to keep focus there.

    Private Sub InspWkPhone_AfterUpdate()
        Select Case Len(Nz(Me.InspWkPhone.Value, vbNullString))
        Case 0, 7, 10
            ' length of value is acceptable so nothing needs to be done
        Case Else
            MsgBox "Check Phone # MISSING digits!"
            Me.InspWkPhone.SetFocus
        End Select
    End Sub
    
    

    That was my attempt to give you what you asked for, but I suggest you consider using the control's BeforeUpdate event instead of AfterUpdate

    Private Sub InspWkPhone_BeforeUpdate(Cancel As Integer)
        Select Case Len(Nz(Me.InspWkPhone.Value, vbNullString))
        Case 0, 7, 10
            ' length of value is acceptable so nothing needs to be done
        Case Else
            MsgBox "Check Phone # MISSING digits!"
            Cancel = True
        End Select
    End Sub