我想通过VBA为动态行数创建数据验证,而每行包含动态列数。
我传递了变量out
,它表示我要设置数据验证的行号,x
是我需要检查验证的最后一列,即我将始终以cell开头( out,2)和公式将延伸到(out,x)。
我尝试了以下代码,但它给了我对象所需的错误。
我想我在代码的Formula
和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(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
另见附图(需要将数据验证添加到黄色部分)。
修改
我已根据评论中的建议对代码进行了一些更改,但我仍然在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 i.e. 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
答案 0 :(得分:1)
您收到错误,因为您尝试使用.Select的返回值作为对象。您也没有为rngRangeToCheck
声明的变量,因此它没有设置为任何内容。您需要先选择Range并使用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"