Can the same code be run for multiple fields on a userform?

gastoff

New Member
Joined
Oct 13, 2015
Messages
25
I have the following code to check if the formatting of the data being entered into the text field:
Code:
Private Sub txtTime1_AfterUpdate()
With txtTime1
   If IsDate(.Value) Then
        .Value = Format(.Value, "HH:MM AM/PM")
    Else
        MsgBox "Input time as HH:MM"
        .Value = ""
        Cancel = True
    End If
End With
End Sub

I have 60 other fields (txtTime2,txtTime3...txtTime60) that need to have the same validation check performed when they are updated. Is there a way to loop through multiple Private Subs or will I need to copy/paste the code and modify it for each individual field?
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
You could move your code into a Standard module as a sub/function then have each AfterUpdate event call that sub/function passing the field value as an argument.

It won't be that much shorter in code lines but it would be easier to maintain if you decided you wanted a change to the code.
 
Upvote 0
I doubt my code will have to change any, but it will be good practice to use the method you detailed. Thanks for the feedback! I'll give it a try when I'm at work later.
 
Upvote 0

Forum statistics

Threads
1,215,767
Messages
6,126,767
Members
449,336
Latest member
p17tootie

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