使用变量在Excel VBA中使用验证:使用变量来定义Operator

时间:2017-07-14 16:19:18

标签: excel vba

我使用引用表来保存变量以定义日期验证。我使用了类似的代码来定义参考表中没有问题的List验证。看来我在使用表驱动值为OPERATOR分配值时遇到了问题。任何帮助表示赞赏。

For Each c In dateFields
              fieldName = "entry_" & c.Value
              validateOperator = "xl" & dropDownSh.Cells(c.Row, c.Column + 1).Value 'list of operator values, e.g., "Between", etc.
              validateStart = dropDownSh.Cells(c.Row, c.Column + 2).Value
              validateStop = dropDownSh.Cells(c.Row, c.Column + 3).Value
              If validateStop = "" Then validateStop = validateStart
              MsgBox (fieldName & ":" & validateList)

              Range(fieldName).Select
              With Selection.Validation
                    .Delete
                    If validateOperator = "xlBetween" Then
                          .Add Type:=xlValidateDate, _
                          AlertStyle:=xlValidAlertStop, _
                          Operator:=validateOperator, _
                          Formula1:=validateStart, _
                          Formula2:=validateStop
                    Else
                          .Add Type:=xlValidateDate, _
                          AlertStyle:=xlValidAlertStop, _
                          Operator:=xlGreaterEqual, _
                          Formula1:=validateStart
                    End If

                    .IgnoreBlank = True
                    .InCellDropdown = True
                    .InputTitle = ""
                    .ErrorTitle = ""
                    .InputMessage = ""
                    .ErrorMessage = ""
                    .ShowInput = True
                    .ShowError = True
              End With
        Next c

1 个答案:

答案 0 :(得分:0)

你不能这样做:

validateOperator = "xl" & dropDownSh.Cells(c.Row, c.Column + 1).Value

然后使用validateOperator,就好像它是一个实际的常量:

'....
If validateOperator = "xlBetween" Then
    .Add Type:=xlValidateDate, _
    AlertStyle:=xlValidAlertStop, _
    Operator:=validateOperator, _
    Formula1:=validateStart, _
    Formula2:=validateStop
Else
'....

您需要传递相应的(例如。xlBetween为1,您可以通过VB编辑器中的对象浏览器找到)或实际常量,而不是表示常量名称的字符串...您可以使用表或函数将字符串映射到它们的等效常量值。