Link to home
Start Free TrialLog in
Avatar of Tocogroup
TocogroupFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How can I 'date format' numerous Excel VBA userform text boxes in a single loop ?

Hi Experts,

I'm creating a user form in Excel VBA and part of the form consists of 12 text boxes which I want to format as date fields dd/mm/yyyy. See attached screenshot.

My code for the first text box is...

' Format the Enquiry date field
   With Me.teEnquiry
      If Not IsDate(.Value) Then
         MsgBox "Invalid date"
      Else
         .Value = Format(.Value, "dd/mm/yyyy")
      End If
   End With

Is there a quicker method of doing this rather than formatting each of the 12 text boxes individually, given that they all have different names ?

Thanks
Toco
Avatar of FamousMortimer
FamousMortimer
Flag of United States of America image

Hi,

This code will loop through each control on userform1
Sub LoopThruControls()
    Dim ctrl As Control
    For Each ctrl In UserForm1.Controls
        MsgBox ctrl.Name
    Next ctrl
End Sub

Open in new window

If, for example, all of your textboxes names start with 'te' you can use this

Sub ValidateDates()
    Dim ctrl As Control
    For Each ctrl In UserForm1.Controls
        If UCase(Left(ctrl.Name, 2)) = "TE" Then
            With ctrl
                If Not IsDate(.Value) Then
                    MsgBox "Invalid date"
                Else
                    .Value = Format(.Value, "dd/mm/yyyy")
                End If
            End With
        End If
    Next ctrl
End Sub

Open in new window

Avatar of Tocogroup

ASKER

I was nearly there with your catch-all code.

Unfortunately I have text boxes which aren't date fields. However, the ones in my example are all enclosed in a frame object called frDelivery. Is there any way I can change your code slightly to just check the text boxes in the frame rather than the whole user form ?
ASKER CERTIFIED SOLUTION
Avatar of FamousMortimer
FamousMortimer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent. I learned a lot from that and it works perfectly.
Many thanks
Toco