我正在尝试为单元格分配验证列表。验证列表是可变的,具体取决于某个单元格的值,例如,如果单元格“C6”的值为28,则验证列表应为Sheet4.Range(" b4:b20")。如您所见,验证列表来自另一张表。为了做到这一点,我编写了以下代码
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中看到的是字符串Rng的值而不是它所代表的范围。 有人可以帮忙吗? 感谢
答案 0 :(得分:1)
问题出在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