Blank cell and restrict input if other cell is "Nothing". Otherwise have drop down list

时间:2018-01-03 09:58:02

标签: vba excel-vba excel

If fx A1 is a drop down list and you choose "Nothing", then B1 should become blank and input should be restricted. If A1 is anything but "Nothing", then B1 should contain a drop down list.

I have tried using data validation, but I don't seem to be able to do it exactly how I want it.

Thanks in advance!

2 个答案:

答案 0 :(得分:0)

在范围内输入您的下拉列表值并命名,让我们说MyList。然后使用名称管理器创建另一个名称,比如RestrictIfNothing。在RefersTo窗口中键入公式:

=IF(Sheet1!$A$1="Nothing", "", MyList)

请记住,地址必须是表格的名称。如果要复制带有验证的单元格,请考虑删除$$。为清楚起见,请参见图片:

enter image description here

然后在您的单元格上设置验证,选择list和= RestrictIfNothing。名称区分大小写,请记住大小写。

要清除B1单元格,请将以下代码粘贴到工作表中(右键单击选项卡并选择'查看代码')

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$1" Then Exit Sub
    If UCase(Target) = "NOTHING" Then Target.Offset(, 1) = ""
End Sub

答案 1 :(得分:0)

您可以将下面的代码粘贴到您有两个下拉列表的工作表的代码表中。它将采取以下行动。

  1. 当A1设置为“Nothing”时,B1将变为空白
  2. 当A1为“Nothing”时选择B1时,选择将跳转到A1

    选项明确

    Const ControlCell As String = "A1"          ' address of dropdown A
    Const TargetCell As String = "B1"           ' address of dropdown B
    Const KeyWord As String = "nothing"
    

    Private Sub Worksheet_Change(ByVal Target As Range)     '201年1月3日

    With Target
        If .Address = Range(ControlCell).Address Then
            If StrComp(.Value, KeyWord, vbTextCompare) = 0 Then
                Application.EnableEvents = False
                Range(TargetCell).ClearContents
                Application.EnableEvents = True
            End If
        End If
    End With
    

    End Sub

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)     '201年1月3日

    With Target
        If .Address = Range(TargetCell).Address Then
            If StrComp(Range(ControlCell).Value, KeyWord, vbTextCompare) = 0 Then
                Application.EnableEvents = False
                Range(ControlCell).Select
                Application.EnableEvents = True
            End If
        End If
    End With
    

    End Sub

  3. 因此,事实上,B1中的下拉列表并未删除。它只是看不见而且无法访问。