所以我有一次數據驗證單元格更改爲三個不同的命名範圍之一基於另一個單元格中的用戶選擇。我需要的是,當用戶選擇某個值,即「選擇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好抓,加我的回答 –