VBA – VBA class modules for buttons
Code reusability is important in any programming language. The main idea is to write as little as possible for easier maintenance. And, as it sometimes happens, writing less is much more difficult, than writing a lot. In the current article, I will present how to check the name of the selected buttons just with a few lines of code, using class modules.

The main idea is to create two classes – one called clsChecker and one clsUfClass. In these, we write the following:
Option Explicit
Public WithEvents btnChecker As MSForms.CheckBox
Private Sub btnChecker_Click()
Dim sText As String
sText = "The value of " & btnChecker.Caption & " is " & IIf((btnChecker.Value = True), "selected", "deselected...") & "."
Debug.Print btnChecker.Enabled
MsgBox sText
End Sub
Option Explicit
Public WithEvents btnOptions As MSForms.OptionButton
Private Sub btnOptions_Click()
Dim sText As String
sText = "You have selected " & btnOptions.Name
MsgBox sText
End Sub
The idea is that the first class returns a message box with the caption of the button and its status (selected or deselected) and the second one returns just the name of the radio button.
Thus, we should simply initialize these classes, once the user form is loaded. This is how it happens:
Option Explicit
Dim optButtons(1 To 3) As New clsUfClass
Dim checkButtons(1 To 2) As New clsChecker
Private Sub UserForm_Initialize()
Dim i As Integer
For i = 1 To 3
Set optButtons(i).btnOptions = Controls("btnOption" & i)
Next i
For i = 1 To 2
Set checkButtons(i).btnChecker = Controls("checkBox" & i)
Next i
End Sub
Private Sub btnExit_Click()
Unload Me
End Sub
The main idea is that this way we assign the click values to the corresponding buttons just with a simple loop. Once it is set, then it stays 🙂 And we may use it as long as the form is loaded.
Enjoy it! 🙂