将数据验证下拉列表中的单词替换为不在选择中的另一个单词

时间:2014-07-22 04:56:58

标签: excel excel-vba vba

我有一个模板,对于列,我有下拉列表,请说 Active Inactive
我的要求是,当我选择 Active 时, A 应该来应该来 Inactive

请帮忙。以下是我到目前为止的代码:

Private Sub Worksheet_Change(ByVal Target As Range)

'if changes in column H and row is > 1 then do the following action

If Target.Column = 8 And Target.Row > 1 Then

'if column D is blank then fill blank in E

If Trim(Cells(Target.Row, Target.Column)) = "" Then
    Cells(Target.Row, Target.Column + 1) = ""

'Else -'lookup for the respective Legislation_code in Temp Sheet

'and fill in the next column
Else
    Cells(Target.Row, Target.Column + 1) = Application.WorksheetFunction.VLookup(Cells(Target.Row, Target.Column), Sheets("Ass_status").Range("A:E"), 4, 0)


'Apply Validation/drop-downlist in the next row

    If Cells(Target.Row + 1, Target.Column) = "" Then

        Application.EnableEvents = False

        Cells(Target.Row, Target.Column).Copy Destination:=Cells(Target.Row + 1, Target.Column)
        Cells(Target.Row + 1, Target.Column) = ""
        Application.EnableEvents = True
    End If

End If
End If
End sub

1 个答案:

答案 0 :(得分:0)

尝试此操作,假设您已设置了如下工作表:

enter image description here

最初使用 B1:B2 中的列表对 A1 进行验证。
然后在同一张表中,使用下面的代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo halt        
    Application.EnableEvents = False
    Dim v As String
    If Not Intersect(Target, [A1]) Is Nothing Then
        With Target
            v = .Value
            .Validation.Delete
            Select Case v
            Case "Active": .Value = "A"
            Case "InActive": .Value = "I"
            End Select
            .Validation.Add xlValidateList, , , "=$B$1:$B$2"
        End With
    End If
forward:
    Application.EnableEvents = True
    Exit Sub
halt:
    MsgBox Err.Description
    Resume forward
End Sub

这是经过测试但数量有限。 HTH。
顺便说一下,您可以明确地进行验证:

.Validation.Add xlValidateList, , , "Active,InActive"

这样,您不需要辅助单元格引用。