Format to mm/yy; Not dd/mm/yy in VBA userform

rahulbassi268

New Member
Joined
Sep 23, 2016
Messages
14
Hello All,

I am building a userform for pharma data entry. The Expiry date is actually just a month & year. Not a date in actual.
So, I have a textbox in userform named Expiry_TxtBox.
I have below requirements:
  1. If user enters 4 characters like 0525, it should get itself modified to 05/25 (It must retain leading zero too)
  2. If user enters slash like 08/26, system should accept it as such.
I am using below snippet, but doesn't work properly. Could use some ideas.

VBA Code:
Private Sub Expiry_TxtBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)

   Expiry_TxtBox.Text = Format$(Expiry_TxtBox.Text, "##/##")

End Sub
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
Maybe this:
VBA Code:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With TextBox1
    If .Text Like "####" Then
        .Text = Left(.Text, 2) & "/" & Right(.Text, 2)
    ElseIf .Text Like "##/##" Then
        'do nothing
    Else
        MsgBox "Wrong input"
        .Text = ""
        Beep
    End If
End With
End Sub
 
Upvote 0
You're welcome, glad to help & thanks for the feedback.:)
And you can add Cancel = True, so if the user enter a wrong input the focus will stay in the textbox. Like this:

VBA Code:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With TextBox1
    If .Text Like "####" Then
        .Text = Left(.Text, 2) & "/" & Right(.Text, 2)
    ElseIf .Text Like "##/##" Then
        'do nothing
    Else
        MsgBox "Wrong input"
        Cancel = True
        .Text = ""
        Beep
    End If
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,139
Messages
6,123,259
Members
449,093
Latest member
Vincent Khandagale

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top