使用VBA进行单元validation

我正在尝试将一个validation列表分配给一个单元格。 如果单元格“C6”的值为28,则validation列表是可变的,例如,如果单元格的值为28,则validation列表应该是范围Sheet4.Range(“b4:b20”)。 正如你所看到的validation列表是从另一个sheet.in为了做到这一点,我写了下面的代码

ValrStart = Sheet4.Cells(rowno, 4).Address 'rowno is the row in which the validation list starts and its value comes from another part of the code ValrEnd = Sheet4.Cells(rownoEnd, 4).Address rownoEnd is the row in which the validation list ends and its value comes from another part of the code Rng = "Sheet4.Range(""" & ValrStart & Chr(58) & ValrEnd & """" & ")" With Cells(20, 3).Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Operator:=xlBetween, Formula1:=Rng .ErrorMessage = "Invalid value. Select one from the dropdown list." check = Cells(20, 3).Validation.Value If check = False Then Cells(20, 3).ClearContents Exit Sub End If End With 

现在发生的是,在我看来,Cell中的值是stringRng的值,而不是它所表示的范围。 任何人都可以帮忙吗? 谢谢

这个问题在Formula1参数中,它的开头必须有一个“=”

我会非常努力的为你做如下工作:

 Dim rng As Range '<~~ set rng as of a Range type With Sheet4 Set rng = .Range(.Cells(rowno, 4), .Cells(rownoEnd, 4)) '<~~ set rng to the wanted range End With With Cells(20, 13).Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Operator:=xlBetween, Formula1:="=" & rng.Address(, , , True) '<~~ have Address function take out the correct formula, just add a "=" at the beginning .ErrorMessage = "Invalid value. Select one from the dropdown list." check = Cells(20, 3).Validation.Value If check = False Then Cells(20, 3).ClearContents Exit Sub End If End With