Excel验证 - 间接列表需要列表和/或编号

时间:2013-03-15 00:03:17

标签: excel excel-vba vba

我有两个带有依赖列表验证的单元格 - 我正在使用INDIRECT根据第一个单元格的值获取第二个单元格的列表/选择框。

我需要做的是更复杂,我正在努力寻找解决方案。

在cellA中,如果选择了value1,则cellB应该有list1(我现在可以这样做) 但是如果选择了cellA value2或value3,则cellB应该需要任何数字 - 而不是列表值。

基本上我需要在一个实例中在cellB中进行列表验证,但在另一个实例中,我需要一个数字验证 - 任何数字。

任何人都可以帮忙吗?欣赏它。

1 个答案:

答案 0 :(得分:0)

我认为他们自动执行此操作的唯一方法是使用VBA来应用正确的验证类型。

以下示例,您不能按原样放入,应该为您提供一些线索,告诉您需要做什么。此代码将放在您正在使用的工作表的工作表代码模块中。

您可以使用宏录制器获取代码以生成所需的验证。

如果您可以使用您的代码和公式更新您的问题,我可以根据您的需要对此进行更多修改。

Private Sub Worksheet_Change(ByVal Target As Range)
' Target is a reference to the Cell(s) that have changed.

    If Target.Address = "$A$1" Then
    ' We only care about this cell (CellA)
        Select Case Target.Value
        Case "needalist"
            ' remove any existing validation and add the list validation to $B$1 (CellB)
            With Sheet1.Range("$B$1").Validation
                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=$C$1:$C$7" ' Formula1 Can contain a formula
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
            End With
        Case "needanumber"
            ' remove any existing validation and add the number validation to $B$1 (CellB)
            With Sheet1.Range("$B$1").Validation
                .Delete
                .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="1", Formula2:="10" ' Formula1 is min, Formula2 is max
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
            End With
        Case Else
            ' Catch Everything
            Sheet1.Range("$B$1").Validation.Delete
        End Select
    End If

End Sub