如何根据单元格值启用按钮

时间:2012-10-04 14:09:42

标签: excel-vba vba excel

我有问题。如何根据单元格值启用/禁用按钮。

在excel表格中我有2个按钮。

我需要做的是。

如果列“L”具有数据

启用一键

否则

“BQ”有数据

需要启用另一个按钮。 其他按钮将被禁用。

如何实现它。

请帮忙...... 提前致谢

2 个答案:

答案 0 :(得分:2)

我正在等待你的答复,如果两者都被填满会发生什么。我在代码中添加了该选项。根据您的需要进行修改。

试试这个

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa

    Application.EnableEvents = False

    CommandButton1.Enabled = False: CommandButton2.Enabled = False

    '~~> If both cols are filled up
    If Application.WorksheetFunction.CountA(Columns(12)) > 0 And _
    Application.WorksheetFunction.CountA(Columns(69)) > 0 Then
        '~~> Change the message as applicable
        MsgBox "Both Columns Cannot have data", vbInformation, "Error"
    Else
        '~~> If Col L is filled up
        If Application.WorksheetFunction.CountA(Columns(12)) > 0 _
        Then CommandButton1.Enabled = True

        '~~> If Col BQ is filled up
        If Application.WorksheetFunction.CountA(Columns(69)) > 0 _
        Then CommandButton2.Enabled = True
    End If
LetsContinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

答案 1 :(得分:0)

将CommandButton1和CommandButton2替换为按钮的名称。

Private Sub Worksheet_Change(ByVal Target As Range)

    If Application.WorksheetFunction.CountA(Range("L:L")) > 0 Then
        CommandButton1.Enabled = True
    Else
        CommandButton1.Enabled = False
    End If

    If Application.WorksheetFunction.CountA(Range("BQ:BQ")) > 0 Then
        CommandButton1.Enabled = False
        CommandButton2.Enabled = True
    Else
        CommandButton1.Enabled = True
    CommandButton2.Enabled = False
End If

End Sub