Enabling/Disabling 按钮基于 Excel VBA 中的条件

Enabling/Disabling Button Based on Condition in Excel VBA

我在 enabling/disabling 基于是否填写了所有 4 个单元格(A2、A4、B2 和 B4)的按钮(表单控件)时遇到了问题。到目前为止,这是我的代码,它们都在同一个 sheet 模块上。

Sub Disable_Button()

Dim myshape As Shape
Set myshape = ThisWorkbook.Worksheets("FORM").Shapes("Button")
With myshape
    .ControlFormat.Enabled = False    '---> Disable the button
    .TextFrame.Characters.Font.ColorIndex = 15    '---> Grey out button label
    .OnAction = ""
End With
End Sub

Sub Enable_Button()

Dim myshape As Shape
Set myshape = ThisWorkbook.Worksheets("FORM").Shapes("Button")
With myshape
    .ControlFormat.Enabled = True    '---> Enable the button
    .TextFrame.Characters.Font.ColorIndex = 1    '---> Highlight button label
    .OnAction = "Module1.TEST"
End With
End Sub

Private Sub Test_Button(ByVal Target As Range)

If Target.Address= 'I'm not sure what to put here since it won't accept multiple ranges
    Application.EnableEvents = False
    If Target.Value = "" Then
    Disable_Button
    Else
    Enable_Button
    End If
    Application.EnableEvents = True
End If
End Sub

Module1.TEST 仅在单元格 C1 中输出“SUCCESS”。我已经分别测试了 Disable_Button 和 Enable_Button,并确认它们可以工作。但是,我在编写代码时遇到问题,该按钮仅在所有 4 个单元格(A2、A4、B2 和 B4)都被填充时才启用。我不确定 ByVal Target As Range 是否可行。感谢您的帮助。

这将进入工作表代码模块:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    
    Set rng = Me.Range("A2:B2,A4:B4") 'the cells to monitor
    'check if any of the cells in `rng` are in `Target`
    If Not Application.Intersect(Target, rng) Is Nothing Then
        ToggleButton (Application.CountA(rng) = 4) 'toggle button
    End If
End Sub

'switch button between enabled/disabled according to `bEnable`
Sub ToggleButton(bEnable As Boolean)
    With Me.Shapes("Button")
        .ControlFormat.Enabled = bEnable
        .TextFrame.Characters.Font.ColorIndex = IIf(bEnable, 1, 15)
        .OnAction = IIf(bEnable, "Module1.TEST", "")
    End With
End Sub