使用excel vba代码,删除单元格中的选定选项时如何返回单元格之前的状态?

问题描述 投票:0回答:1

我有一个简单的担忧,就是将一系列单元格的单元格返回到其先前的状态(通常单元格包括使用 DATA>DATA VALIDATION 部分生成的数据验证列表)。

我有一个宏,允许我在从下拉列表中选择“无”选项时删除单元格中的数据验证列表。

这是我正在使用的代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Cells As Range
    Dim DV As Range
    Dim isect2 As Range
    Dim valid As Validation
    Set DV = Range("K3:K28")
    Set isect2 = Intersect(Target, DV)
    Set valid = Selection.Validation
    If isect2 Is Nothing Then
        Exit Sub
    Else
        For Each Cells In isect2
            If Cells.Value = "None" Then
                Set valid = Selection.Validation
                Selection.Validation.Delete
            Else
                **Application.EnableEvents = False**
            End If
        Next Cells
    End If
End Sub

当单元格中选定的选项(“无”)被删除时,我想将单元格返回到之前的状态(恢复相同的数据验证列表)。

编辑

Sub Macro7(ByVal Target As Range)

Dim Cells As Range
Dim DV As Range
Dim isect2 As Range
Dim valid As Validation

    Set DV = Range("K3:K28")
    Set isect2 = Intersect(Target, DV)
    
    Set valid = Selection.Validation
    If isect2 Is Nothing Then
        Exit Sub
    Else
        For Each Cells In isect2    
            If Cells.Value = "None" Then
        
                Set valid = Selection.Validation
                Selection.Validation.Delete
        
            ElseIf IsEmpty(Cells.Value) = True Then
        
                With Selection.Validation
                    .Delete
                    .***Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                xlBetween, Formula1:="=sheet4!$A$2:$A$18"***        
                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .InputTitle = ""
                    .ErrorTitle = ""
                    .InputMessage = ""
                    .ErrorMessage = ""
                    .ShowInput = True
                    .ShowError = True
                End With
        
            End If    
        Next Cells
    End If
End Sub
excel vba undo
1个回答
0
投票

这对我有用:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range, isect2 As Range
    
    Set isect2 = Intersect(Target, Me.Range("K3:K28"))
    
    If Not isect2 Is Nothing Then
        For Each c In isect2.Cells
            If c.Value = "None" Then
                c.Validation.Delete
            ElseIf IsEmpty(c.Value) Then
                With c.Validation
                    .Delete
                    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
                         Operator:=xlBetween, Formula1:="=sheet4!$A$2:$A$18"
                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .ShowInput = True
                    .ShowError = True
                End With
            End If
        Next c
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.