Shorten OptionButton code

Drmwvr7266

Board Regular
Joined
Apr 7, 2002
Messages
164
Is there a way to shorten this code? I'm assuming that maybe if I used a group name, such as "widgets", that I can shorten it.


Private Sub Commandbutton1_Click()

If OptionButton1.Value = True Then
Topleft
Exit Sub
Else
If OptionButton2.Value = True Then
TopRight
Exit Sub
Else
If OptionButton3.Value = True Then
Bottomleft
Exit Sub
Else
If OptionButton4.Value = True Then
BottomRight
Exit Sub
Else
If OptionButton5.Value = True Then
Deadcenter
Exit Sub
Else
MsgBox "You need to select a position for your message", , "Select Position"
End If
End If
End If
End If
End If

End Sub


Any ideas?
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
You can use ElseIf:

Code:
Private Sub Commandbutton1_Click() 
   If OptionButton1.Value = True Then 
      Topleft 
   ElseIf OptionButton2.Value = True Then 
      TopRight 
   ElseIf OptionButton3.Value = True Then 
      Bottomleft 
   ElseIf OptionButton4.Value = True Then 
      BottomRight 
   ElseIf OptionButton5.Value = True Then 
      Deadcenter 
   Else
      MsgBox "You need to select a position for your message", , "Select Position" 
   End If 
End Sub
 
Upvote 0
I don't know that this is any more efficient, but it is easier to read.
<pre>
Private Sub Commandbutton1_Click()
Select Case True
Case OptionButton1.Value: Topleft
Case OptionButton2.Value: TopRight
Case OptionButton3.Value: Bottomleft
Case OptionButton4.Value: BottomRight
Case OptionButton5.Value: Deadcenter
Case Else: MsgBox "You need to select a position" & _
" for your message", , "Select Position"
End Select
End Sub

</pre>
Tom
 
Upvote 0

Forum statistics

Threads
1,222,408
Messages
6,165,870
Members
451,989
Latest member
DannyBoy1977

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