选项按钮编号循环



希望您能为一个可能很简单的问题找到一个优雅的解决方案!

我使用ActiveX选项按钮,但在工作表中,而不是用户窗体或组框中,因为工作表的设计方式。该代码作为子代码包含在选项按钮代码表单中。

这段代码很好地解释了我要做的事情:

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"类型语句来更改值,但VBA变量/表达式/对象的某些限制似乎不允许我这样做(对不起,我在这里是个傻瓜,不确定正确的术语应该是什么)。

如果有人能在这里为我指明正确的方向,我将不胜感激!我必须查看大约25个选项按钮对,我非常希望代码只有5行简单的代码,而不是100多行做同样的事情!

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

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

最新更新