2016-11-29 60 views
1

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

Option Explicit 

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

这里“A”被声明为整数,并且“10”已被存储在“A”而不会出现错误。 有没有一种方法可以在每个字符串赋值时显示错误,例如在其他编程语言中。

+1

它知道到' “',尝试把'一=” 字符串1中读出的值“'看看会发生什么...... –

+2

这是由[隐式转换]引起的(http://bettersolutions.com/vba/data-ty PES /转换隐-conversion.htm)。 – dee

+1

这被称为隐式类型转换。 “10”隐式转换为整数10.因此,整型变量不会**存储一个字符串,而是一个隐式转换整数。不仅'VBA'会这样做,还有一些其他的编程语言。据我所知,你无法在'VBA'中避免这种情况。 –

回答

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 

此功能可被包裹在一个例如命名的类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 
相关问题