为什么整型variables在VBA Excel中存储string值

我已经声明了一个整数types的variables。 VBA Excel不限制只存储整数。 它接受string值(如“10”),并在消息框中正确显示10。 我想要一个整数variables只能存储整数值的解决scheme。 示例代码是

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

这里“a”被声明为整数,“10”被存储在“a”中,没有错误。 有没有一种方式,如每个string分配,如其他编程语言显示错误。

一个快速的想法可能是将新值存储在Varianttypes的variables中,并在赋值给Integervariables之前检查其子types。

  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 

这个function可以被包装在一个名为例如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 

标准模块testing

 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