使用VBA创builddynamicvalidation列表:对象必需

我想通过VBA为dynamic数字的行创build数据validation,而每行都包含dynamic数量的列。 我传递了variablesout ,它表示要设置数据validation的行号, x是我需要检查validation的最后一列,即我将始终以cell(out,2)开始,公式将会扩展直到(out,x)。 我试过下面的代码,但它给我的对象所需的错误。 我认为我在代码的FormulaSomeNamedRange部分中犯了一些错误。 我应该在代码中做些什么改变,以及我在想什么错误?

 Sub DataValidation(out As Integer, x As Integer, y As Integer) Sheets("first_sheet").Select ActiveSheet.Range(Cells(out, 2), Cells(out, x)).Name = "SomeNamedRange" Dim RangeToCheck As Excel.Range Set RangeToCheck = ActiveSheet.Range(Cells(2, 1), Cells(3, 10)) Dim choice Set choice = "=SomeNamedRange" With rngRangeToCheck.Select Selection.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 End Sub 

另见附图(数据validation应该需要添加到黄色部分)。 在这里输入图像说明

编辑:

我已经对注释中的build议做了一些更改,但是我仍然在Set choice = "=SomeNamedRange"

更改代码如下:

 Sub DataValidation(out As Integer, x As Integer, y As Integer) Sheets("first_sheet").Select ActiveSheet.Range(Cells(out, 2), Cells(out, x)).Name = "SomeNamedRange" Dim RangeToCheck As Excel.Range Set RangeToCheck = ActiveSheet.Range(Cells(out, 2), Cells(out, x)) Dim choice As String Set choice = "=SomeNamedRange" 'y is the column number where I want validation ie yellow column in picture With RangeToCheck.Cells(out, y).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 End Sub 

你得到一个错误,因为你试图使用.Select的返回值作为一个对象。 你也没有为rngRangeToCheck声明一个variables,因此它没有设置任何东西。 您需要先selectRange,然后使用Selection对象或直接使用Range:

 With RangeToCheck.Validation 'Do stuff '... End With 'Or RangeToCheck.Select With Selection.Validation 'Do stuff '... End With 

第二个问题是这些行:

 Dim choice Set choice = "=SomeNamedRange" 

你隐式地把“choice”声明为一个Variant,但是你正在使用Object语法为它分配一个String。 它应该是:

 Dim choice As String choice = "=SomeNamedRange"