如何将变量分配给Excel VBA中的数据验证公式1:=?

时间:2015-07-07 12:12:34

标签: excel vba validation

我正在尝试将变量Rng分配给Formula1:=.

Function DisplayName()

Dim iLastRow As Integer ' This variable will get Last Cell which is not empty in a Column
Dim Rng As Variant ' This variable is created for Dynamic Range selection in a sheet2 named as "BM"

Dim sheetRef As Worksheet
Set sheetRef = Sheets("BM")

iLastRow = sheetRef.Cells(Rows.Count, "A").End(xlUp).Row
Rng = sheetRef.Range("A2:A" & iLastRow)

    With ActiveCell.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
          Operator:=xlBetween, Formula1:=Rng
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = "Select From List"
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

End Function

以下错误消息指向.Add Type:=

  

运行时错误'1004':应用程序定义的错误或对象定义的错误

如果我删除变量并将"=Sheet2!A2:A99"置于其中。

3 个答案:

答案 0 :(得分:1)

我遇到了类似的问题,没有通过... With ActiveCell.Validation: .Delete: .Add ...尝试过,而是通过 .Modify ... Formula1是只读的)尝试了,它起作用:

ActiveCell.Validation.Modify Formula1:= ...

(因此,使用您的代码,值可以为"=Sheet2!A2:A99"sheetRef.Range("A2:A" & iLastRow).TextRng.Text(使用Set时不需要.Text)。

答案 1 :(得分:0)

更改Set类型变量的值时,您需要使用Range关键字。将您的行更改为:

Set Rng = sheetRef.Range("A2:A" & iLastRow)

See here了解更多信息。

答案 2 :(得分:0)

对于类似的问题,这基本上对我有用。 Formula1参数接受字符串,因此...

Function DisplayName()

    Dim iLastRow As Integer ' This variable will get Last Cell which is not empty in a Column
    Dim formulaString As String

    iLastRow = Sheets("BM").Cells(Rows.Count, "A").End(xlUp).Row
    formulaString = "='BM'!A2:A" & iLastRow

    With ActiveCell.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Operator:=xlBetween, Formula1:=formulaString
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = "Select From List"
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

End Function