一個快速的想法可能是將新值存儲在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'中避免這種情況。 –