为什么整数变量在VBA Excel中存储字符串值

时间:2016-11-29 07:37:05

标签: excel vba excel-vba

我已经声明了一个整数类型的变量。 VBA Excel不限制只在其中存储整数。它接受字符串值(例如" 10")并在消息框中正确显示10。 我想要一个解决方案,其中整数变量只能存储整数值。 示例代码是

    Option Explicit

    Sub Button1_Click()
        Dim a As Integer
        a = "10"
        MsgBox (a)
   End Sub

这里' a'被声明为整数和" 10"已被存储在' a'没有错误。 有没有办法在每个字符串赋值中显示错误,例如在其他编程语言中。

1 个答案:

答案 0 :(得分:2)

一个简单的想法可能是将新值存储在Variant类型的变量中,并在赋值给Integer变量之前检查其子类型。

 Sub Button1_Click()
    Dim newIntegerValue As Variant
    newIntegerValue = "10"

    If VarType(newIntegerValue) = vbString Then
        Err.Raise 123, "Button1_Click", "Invalid cast"
    End If

    Dim a As Integer
    a = newIntegerValue
End Sub

此功能可以包含在一个名为eg的类中StrictInteger

  

StrictInteger类模块

Option Explicit

Private m_value As Integer
Private m_hasValue As Boolean
Private Const invalidValueErrorNumber As Long = vbObjectError + 600

Private Sub Class_Initialize()
    m_value = 0
    m_hasValue = False
End Sub

Public Function Assign(ByVal newIntegerValue As Variant)
    ' TODO: check with next variant sub types
    If VarType(newIntegerValue) = vbString Or _
        VarType(newIntegerValue) = vbBoolean Then
        Err.Raise invalidValueErrorNumber, _
            "StrictInteger::Initialize", _
            "Value initialization failed"
    End If
    On Error GoTo Err_Initialize
    m_value = newIntegerValue
    m_hasValue = True
    Exit Function
Err_Initialize:
    m_hasValue = False
    Err.Raise Err.Number, "StrictInteger::Initialize", Err.Description
End Function

Public Property Get Value() As Integer
    If m_hasValue Then
        Value = m_value
        Exit Property
    End If
    Err.Raise invalidValueErrorNumber, _
        "StrictInteger::Value", _
        "Valid value is not available"
End Property
  

标准模块测试

Sub Test()
    On Error GoTo Err_Test
    Dim strictInt As StrictInteger
    Set strictInt = New StrictInteger
    strictInt.Assign "10"
    strictInt.Assign "ABC"
    strictInt.Assign ActiveSheet
    strictInt.Assign Now
    strictInt.Assign True
    strictInt.Assign False
    strictInt.Assign 10
    MsgBox strictInt.Value
    Exit Sub
Err_Test:
    MsgBox Err.Number & ". " & Err.Description, vbCritical, "Error"
    Resume Next
End Sub