输入数据时,在同一行中自动清除数据验证

时间:2018-02-15 21:00:40

标签: excel excel-vba vba

我想出了以下内容,当我将一个值输入到第V列的单元格中时,我试图用它来清除单元格中的数据验证(同一行,W列)。 我在W列中有一个下拉数据选择,每当我在V列中输入数据时,我试图擦除同一行的清理。例如,如果在V4中输入数据,则单元格W4现在是一个没有验证的空白单元格

为什么我不能让这个工作的任何想法?

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim wsSource As Worksheet
    Dim rowCount As Long


    Set wsSource = Worksheets("Attributes")

    Application.ScreenUpdating = False

    With wsSource
    rowCount = .Cells(.Rows.Count, "V").End(xlUp).Row 
    For i = 1 To rowCount
        If .Cells(i, "V").Value <> 0 Then

        ActiveCell.Offset(0, 1).Select
        Range.Cells(i, "W").ClearContents
            With Selection.Validation
            .Delete
            .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
            :=xlBetween
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = True
            End With
        End If
    Next i
    End With


End Sub

1 个答案:

答案 0 :(得分:0)

看来问题就在于这一点:

ActiveCell.Offset(0, 1).Select 'delete this one because is selecting column by column

Cells(i, "W").ClearContents 'delete `Range.` it is redundant

如果您只想清理W栏中的数据,只需要:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim wsSource As Worksheet
    Dim rowCount As Long

    Set wsSource = Worksheets("Attributes")

    Application.ScreenUpdating = False

    With wsSource
    rowCount = .Cells(.Rows.Count, "V").End(xlUp).Row
    For i = 1 To rowCount
        If .Cells(i, "V").Value <> 0 Then
        Cells(i, "W").ClearContents
        End If
    Next i
    End With
End Sub