使用变量时,通过excel中的VBA设置验证失败

Gra*_*atc 4 excel vba excel-vba

我正在尝试使用VBA为一系列单元格设置数据验证.我用这段代码得到了运行时错误1004(非常有帮助)"应用程序定义或对象定义错误".

 With rngRangeToCheck.Cells(lrownum, 1).Validation
    .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=choice
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
End With
Run Code Online (Sandbox Code Playgroud)

在Formula1中,choice是一个传递给函数的变量,类似于代码所在的工作簿中的"= SomeNamedRange".

错误发生在.Add代码部分.

如果我在Formula1:="=SomeNamedRange"没有问题的情况下对Formula1进行硬编码.我真的宁愿不对它进行硬编码,因为我正在使用"选择"的许多可能值来做这个,而这只是不太干净的代码, 我认为.

我已经烧了谷歌和大约3本不同的书现在试图解决这个问题.

有什么建议?感谢您帮助新手.

Gru*_*les 5

这也许应该是一个评论,特别是因为这篇文章太老了......我遇到了同样的问题,它会在某些时候工作而不是其他工作.使用动态命名的范围.我找到的解决方案是暂时解锁工作表.

Private Sub FixDropdownLists()

Sheet1.Unprotect Password:="afei31afa"
Dim cellv As Range

For Each cellv In Sheet1.Range("B18:E18,B32:E32")
    With cellv.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=Office_Locations"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = "Invalid Input"
        .InputMessage = ""
        .ErrorMessage = "Select the location only from the dropdown list."
        .ShowInput = False
        .ShowError = True
    End With
Next cellv
Sheet1.Protect Password:="afei31afa"
End Sub
Run Code Online (Sandbox Code Playgroud)