VBA数据验证列表选择

时间:2015-09-30 03:49:38

标签: excel vba excel-vba

我正在编写一个嵌入一个表的代码。情况是这样的: 单元格A1(选项为50,100和150)和单元格A2(选项为1000和5000)都包含数据验证列表。当我选择单元格A1为50时,A2必须为1000.当我编写代码并进行选择时,总会出现错误:

  

运行时错误'-2147417848(80010108)':对象'验证'的方法'添加'失败。

请分享您的意见,或者如果需要,我可以在此处发布我的代码以解决此问题。

基本代码如下:

Select Case Range("A1").Value
Case "50"
         Range("A2").ClearContents
        Range("A6").Value2 = "1000"

Case "`100"
         Range("A2").ClearContents
       With Range("A2").Validation
        .Delete
        .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
        :=xlBetween
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
        Range("A2").Value2 = 1000

1 个答案:

答案 0 :(得分:0)

将此代码添加到工作表的模块中,并将要验证的单元格添加到

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = "$A$1" Then

        If Target.Value = 50 Then

             Range("A2") = 1000

            ' Add valid values of 1000 allowed only
            With Range("A2").Validation
                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="1000"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = "Enter a valid value"
                .ShowInput = False
                .ShowError = True
            End With

        Else
            ' Add valid values of 1000 and 5000 allowed
            With Range("A2").Validation
                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="1000,5000"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = "Enter a valid value"
                .ShowInput = False
                .ShowError = True
            End With
        End If




    End If

End Sub