在变量上设置数字约束

时间:2017-09-12 08:45:06

标签: excel vba excel-vba constraints

在VBA中创建变量时有没有办法设置约束?

实施例: dim alfa as integer

现在我希望Excel接受仅从0到99 的值,我该怎么做?

非常感谢

2 个答案:

答案 0 :(得分:4)

您可以像这样验证:

Sub Test()
    Dim i As Integer
    i = 100

    If Not (i >= 0 And i <= 99) Then Err.Raise Number:=6, Description:="Number not valid"

    'continue to use i
End Sub

您还可以创建一个新类,它只接受某些值。在大多数情况下,这将是矫枉过正,但在这里:

将其放入标准模块

Sub Test()
    Dim specialNumber As SNumber
    Set specialNumber = New SNumber

    specialNumber.Value = 1
    specialNumber.Value = 100 'this line will throw an error
End Sub

然后将其放入类模块并将模块命名为 SNumber

Private specialNumber As Integer

Public Property Get Value() As Integer
    Value = specialNumber
End Property

Public Property Let Value(v As Integer)
    If Not (v >= 0 And v <= 99) Then
        Err.Raise Number:=6, Description:="Number not valid"
    Else
        specialNumber = v
    End If
End Property

答案 1 :(得分:0)

这样做的好方法是在Excel中使用数据验证。

Sub TestMe()
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, _
              Operator:=xlBetween, Formula1:="=AND(A1>=0, A1<=100, ISNUMBER(A1))"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End Sub

现在A1只会介于1和100之间,而且会是一个数字。