How can I simplify the code

yasawa

New Member
Joined
Dec 29, 2011
Messages
21
Hello
I have this code working on a form, it's working fine, simply writing the caption in the sheet if the box is checked...
I tried using variables, using loops and many other methods to get the same result without having to repeat the lines over and over but none worked


Private Sub OKButton1_Click()

Worksheets("Path").Activate

emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
Cells(emptyRow, 1).Select


If CheckBox1.Value = True Then
ActiveCell.Value = CheckBox1.Caption
ActiveCell.Offset(1, 0).Select
End If

If CheckBox2.Value = True Then
ActiveCell.Value = CheckBox2.Caption
ActiveCell.Offset(1, 0).Select
End If

If CheckBox3.Value = True Then
ActiveCell.Value = CheckBox3.Caption
ActiveCell.Offset(1, 0).Select
End If

If CheckBox4.Value = True Then
ActiveCell.Value = CheckBox4.Caption
ActiveCell.Offset(1, 0).Select
End If

If CheckBox5.Value = True Then
ActiveCell.Value = CheckBox5.Caption
ActiveCell.Offset(1, 0).Select
End If

Unload Me

End Sub
 
I highlighted in blue the part that replaces your repeated If..Then code blocks...

Code:
Private Sub OKButton1_Click()
  [B][COLOR=#0000ff]Dim Cntrl As Control[/COLOR][/B]
  Worksheets("Path").Activate

  emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
  Cells(emptyRow, 1).Select
  
[B][COLOR=#0000ff]  For Each Cntrl In Me.Controls
    If TypeName(Cntrl) = "CheckBox" Then
      If Cntrl.Value Then
        ActiveCell.Value = Cntrl.Caption
        ActiveCell.Offset(1).Select
      End If
    End If
  Next[/COLOR][/B]
  
  Unload Me

End Sub

NOTE: As written, the loop processes every CheckBox on the UserForm. If you have some CheckBoxes that need to be ignored, you will have to add code in the loop to look for those names in order to skip them.
 
Last edited:
Upvote 0

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