一个快速的想法可能是将新值存储在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
来源
2016-11-29 08:04:08
dee
它知道到' “',尝试把'一=” 字符串1中读出的值“'看看会发生什么...... –
这是由[隐式转换]引起的(http://bettersolutions.com/vba/data-ty PES /转换隐-conversion.htm)。 – dee
这被称为隐式类型转换。 “10”隐式转换为整数10.因此,整型变量不会**存储一个字符串,而是一个隐式转换整数。不仅'VBA'会这样做,还有一些其他的编程语言。据我所知,你无法在'VBA'中避免这种情况。 –