提问人:PYC 提问时间:8/28/2023 最后编辑:Tim WilliamsPYC 更新时间:8/31/2023 访问量:82
使用Excel VBA代码,在删除单元格中的seleted选项时,如何返回单元格的先前状态?
with excel vba code, how can return the cell it's previous state when deleting seleted option in the cell?
问:
我有一个简单的担忧,即将单元格恢复到以前的状态(通常单元格包括使用 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
当单元格中删除所选选项(“none”)时,我想将单元格恢复到以前的状态(恢复相同的数据验证列表)。
编辑
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
答:
1赞
Tim Williams
8/31/2023
#1
这对我有用:
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
评论
0赞
PYC
9/1/2023
您提供的代码就像一个魅力..非常感谢您的努力和时间。
0赞
PYC
9/1/2023
仅代码就非常好用。但是,如果有其他代码(无论代码是什么;我一一尝试了所有代码),它总是为同一行提供运行时错误 1004。难道是因为我不得不将这段代码与其他代码一起编写为子宏吗?
0赞
Tim Williams
9/1/2023
如果不看其他代码,我很难知道。如果重命名它并从 中调用它作为参数传入,它应该以相同的方式工作,但不能确定。Worksheet_Change
Target
评论