OptionButton编号循环

希望你有一个优雅的解决scheme,可能是一个简单的问题!

我正在使用ActiveX选项button,但在工作表中,而不是一个用户窗体或一个组框,因为工作表的devise方式。 该代码包含在一个选项button代码forms内的一个子。

这段代码很好理解了我正在做的事情:

Public Sub SectionD_Click() If OptionButton1.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B2").Value = 1 ElseIf OptionButton2.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B2").Value = 0 End If If OptionButton3.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B3").Value = 1 ElseIf OptionButton4.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B3").Value = 0 End If If OptionButton5.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B4").Value = 1 ElseIf OptionButton6.Value = True Then ThisWorkbook.Sheets("Boolean").Range("B4").Value = 0 End If End Sub 

我想这样做使得“OptionButton”后面的数字使用简单的“i = i + 2”types的语句来更改值,但是似乎有些VBAvariables/expression式/对象的限制不会让我(对不起,我是noob在这里,不知道什么是适当的术语)。

如果有人能指出我在这里正确的方向,真的很感激! 我必须查看25个左右的选项button对,我非常希望代码只是5个简单的线条,而不是一百多条线条做同样的事情!

我可以用一行代码来命名这个曲子!

 Public Sub SectionD_Click(): Dim i As Integer: Dim rw As Long: rw = 2: With Worksheets("Sheet1"): For i = 1 To 10 Step 2: If .OLEObjects("OptionButton" & i).Object.Value Then: Worksheets("Boolean").Cells(rw, "B").Value = 0: ElseIf .OLEObjects("OptionButton" & i).Object.Value Then: Worksheets("Boolean").Cells(rw, "B").Value = 0: End If: rw = rw + 1: Next: End With:End Sub: 

但是我觉得16条线比较漂亮。

 Public Sub SectionD_Click() Dim i As Integer Dim rw As Long rw = 2 With Worksheets("Sheet1") For i = 1 To 10 Step 2 If .OLEObjects("OptionButton" & i).Object.Value Then Worksheets("Boolean").Cells(rw, "B").Value = 0 ElseIf .OLEObjects("OptionButton" & i).Object.Value Then Worksheets("Boolean").Cells(rw, "B").Value = 0 End If rw = rw + 1 Next End With End Sub 

5行? 真? :)这是我能做的最好的:

 Option Explicit Public Sub SectionD_Click() With ThisWorkbook.Sheets("Boolean") Call CheckValue(.OptionButton1, .OptionButton2, .Range("B2")) Call CheckValue(.OptionButton3, .OptionButton4, .Range("B3")) End With End Sub Sub CheckValue(btn1 As Object, btn2 As Object, my_cell As Range) If btn1.Value Then my_cell.Value = 1 ElseIf btn2.Value Then my_cell = 0 End If End Sub