Reduce code for Change event for multiple TextBoxes and ComboBoxes

AndyEd

Board Regular
Joined
May 13, 2020
Messages
124
Office Version
  1. 365
Platform
  1. Windows
I have the following code used to check if there is a value displayed in TextBoxes and ComboBoxes. The code is fired via ComboBox change event.

VBA Code:
    With Me.tbxFileOpenDate
        If .Value = vbNullString Then
            .BackColor = RGB(255, 242, 204)
        Else
            .BackColor = vbWhite
        End If
    End With

The issue is that I have in excess of 50 such objects on the UserForm. Is there way to apply the code to all the objects without having to code for them individually?

Thank you in advance.
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
Hi AndyEd. This seems like it might work if your controls were generically named (ie. Textbox1, Textbox2, etc.) Don't think it will work for named controls? Maybe the loop mechanics will help you. Dave
Code:
Sub test()
Dim ctl As Control
For Each ctl In Userform1.Controls
If InStr(ctl.Name, "TextBox") = True Or _
InStr(ctl.Name, "ComboBox") = True Then
If ctl.Value = vbNullString Then
    ctl.BackColor = RGB(255, 242, 204)
Else
    ctl.BackColor = vbWhite
End If
End If
Next ctl
End Sub
 
Upvote 0
Another user provided the following cleanup whilst looking at another issue I had.


VBA Code:
Private Sub cboSelectFile_Change()
Call EmptyCheck(Me.tbxFileOpenDate)
:
:
End Sub

Private Sub EmptyCheck(ByRef Ctrl As Object)    'TextBox or ComboBox
    With Ctrl
        If .Value = vbNullString Then
            .BackColor = RGB(255, 242, 204)
        Else
            .BackColor = vbWhite
        End If
    End With
End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,223,246
Messages
6,170,988
Members
452,373
Latest member
TimReeks

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