所以我有一次数据验证单元格更改为三个不同的命名范围之一基于另一个单元格中的用户选择。我需要的是,当用户选择某个值,即“选择A”时,数据验证不仅会改变到相应的命名范围,而且还会显示该范围内的第一个值。VBA数据验证默认值从命名范围
目前我可以操作代码来获取默认值,但是每次尝试并做出选择时,它都会一直变回默认值。这甚至有可能吗?下面是我的代码,我在一次特定的命名范围内使用Worksheet_Change事件
在这个例子中当前运行的,我用了一个名为范围selection_a
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("$E$3").Value = "Selection A" Then
With Range("L3:R4").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=selection_a"
.IgnoreBlank = False
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End If
使用默认值显示和变回不断:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("$E$3").Value = "Selection A" Then
Range("$L$3").Value = Sheets("sheet2").Range("$M$4").Value
With Range("L3:R4").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=selection_a"
.IgnoreBlank = False
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End If
您应该在您的事件处理代码中禁用事件,因为您正在更改单元格。相关:http://stackoverflow.com/questions/13860894/ms-excel-crashes-when-vba-code-runs/13861640#13861640 –
@Byron好抓,加我的回答 –