我正在尝试将变量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"
置于其中。
答案 0 :(得分:1)
我遇到了类似的问题,没有通过... With ActiveCell.Validation: .Delete: .Add ...
尝试过,而是通过 .Modify ...
(Formula1
是只读的)尝试了,它起作用:>
ActiveCell.Validation.Modify Formula1:= ...
(因此,使用您的代码,值可以为"=Sheet2!A2:A99"
,sheetRef.Range("A2:A" & iLastRow).Text
或Rng.Text
(使用Set
时不需要.Text
)。
答案 1 :(得分:0)
答案 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