将范围分配给数据验证-VBA

时间:2019-09-03 13:15:35

标签: excel vba validation

我正在尝试通过数据验证范围,但是我收到错误。有什么想法吗?

以下错误:

.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=rng

错误:

enter image description here

代码:

Option Explicit

Sub test()

    Dim rng As Range

    Set rng = wsIndex.Range("A1:A5")

        With wsIndex.Range("K1").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=rng
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

End Sub

2 个答案:

答案 0 :(得分:2)

DataValidation不会只接受Range的{​​{1}},因此您可以这样做:

String因为需要一个公式。

答案 1 :(得分:1)

虽然您可以引用范围(按照@Damian),但也可以使用数组:

Option Explicit

Sub test()

Dim lst As Variant
lst = Application.Transpose(wsIndex.Range("A1:A5"))
With wsIndex.Range("K1").Validation
    .Delete
    .Add Type:=xlValidateList, Formula1:=Join(lst, ",")
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

End Sub