如何将variables分配给数据validation公式1:= in excel vba?

请帮我在下面的代码。

在这里,我正在尝试将一个variablesRng分配给Formula1:=.

如果我删除variables,并放置"=Sheet2!A2:A99"它的作品。

以下错误消息正在获取&光标指向.Addtypes:=

错误代码:

Run-time error '1004': Application-defined or object-defined error

VBA代码:

 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 

更改Rangetypes的variables的值时,需要使用Set关键字。 将您的行更改为:

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

在这里看到更多的信息。