繁体   English   中英

使用VBA进行单元验证

[英]cell validation using VBA

我正在尝试将验证列表分配给单元格。 验证列表是可变的,具体取决于某个单元格的值,例如,如果单元格“ 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

现在发生的是,在单元格中出现的是字符串Rng的值,而不是它表示的范围。 有人可以帮忙吗? 谢谢

问题出在Formula1参数中,该参数的开头必须为“ =”

我希望excel可以为您完成艰苦的工作,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM