简化切换按钮更改BackColor代码VBA

时间:2016-12-05 06:48:48

标签: vba excel-vba excel

我是VBA制作的新手,所以下面的所有代码仍在工作,但需要很多代码。即使它更容易维护,但如果有人可以简化我的noob-code来削减一些线条和更令人愉悦的?

我的用户表单中有超过20个切换按钮

这是我的代码示例,需要帮助才能使其更简单

Private Sub tgglC_Result1_Click()
If tgglC_Result1.Value = True Then
    tgglC_Result1.BackColor = &HFF00&
    tgglNC_Result1.Enabled = False
    lblResult1.Caption = Now
    lblResult1.Visible = True
Else
    tgglC_Result1.BackColor = &H8000000F
    tgglNC_Result1.Enabled = True
    lblResult1.Visible = False
End If
End Sub
Private Sub tgglC_Result2_Click()
If tgglC_Result2.Value = True Then
    tgglC_Result2.BackColor = &HFF00&
    tgglNC_Result2.Enabled = False
    lblResult2.Caption = Now
    lblResult2.Visible = True
Else
    tgglC_Result2.BackColor = &H8000000F
    tgglNC_Result2.Enabled = True
    lblResult2.Visible = False
End If
End Sub
Private Sub tgglC_Result3_Click()
If tgglC_Result3.Value = True Then
    tgglC_Result3.BackColor = &HFF00&
    tgglNC_Result3.Enabled = False
    lblResult3.Caption = Now
    lblResult3.Visible = True
Else
    tgglC_Result3.BackColor = &H8000000F
    tgglNC_Result3.Enabled = True
    lblResult3.Visible = False
End If
End Sub
Private Sub tgglC_Result4_Click()
If tgglC_Result4.Value = True Then
    tgglC_Result4.BackColor = &HFF00&
    tgglNC_Result4.Enabled = False
    lblResult4.Caption = Now
    lblResult4.Visible = True
Else
    tgglC_Result4.BackColor = &H8000000F
    tgglNC_Result4.Enabled = True
    lblResult4.Visible = False
End If
End Sub

2 个答案:

答案 0 :(得分:0)

最好的方法应该是使用Class

但更“传统”的方式也可以帮助你减轻打字负担:

  • 定义一个唯一的切换控件处理子

        Private Sub tgglC_Result_Click()
            Dim NC As Control
    
            With Me
                Set NC = .Controls(VBA.Replace(.ActiveControl.Name, "tgglC", "tgglNC")) '<--| set the "counter part" toggle button control of the "Active" control (i.e. the one being currently toggled)
                With .ActiveControl
                    .BackColor = IIf(.Value, &HFF00&, &H8000000F)
                    NC.Enabled = Not .Value
                End With
            End With
        End Sub
    
  • 从任何事件处理程序

    中调用它
    Private Sub tgglC_Result1_Click()
        tgglC_Result_Click
    End Sub
    
    Private Sub tgglC_Result2_Click()
        tgglC_Result_Click
    End Sub
    
    Private Sub tgglC_Result3_Click()
        tgglC_Result_Click
    End Sub
    
    ...
    

答案 1 :(得分:0)

这不是一个简化的解决方案,但这是我在需要为Access子窗体上的60多个控件提供逻辑时所使用的(与您的类似任务):

Sub makeCode()
Dim i As Integer    
For i = 1 To 4
        Debug.Print "Private Sub tgglC_Result" & i & "_Click()"
        Debug.Print "tgglC_Result" & i & ".BackColor = &HFF00&"
        Debug.Print "tgglNC_Result2.Enabled = False"
        Debug.Print "lblResult" & i & ".Caption = Now"
        Debug.Print "lblResult" & i & ".Visible = True"
        Debug.Print "End Sub"
        Debug.Print ""
    Next
End Sub

将结果从立即窗口复制到代码编辑器中。修改所有子程序也很容易:只需更改循环体,运行它,然后替换旧代码。