One quick idea could be to store the new value in a variable of type Variant and prior to assignment to the Integer variable check its sub type.
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
This functionality could be wrapped in a class named e.g. StrictInteger.
StrictInteger class module
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
Standard module test
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
", try puttinga = "string1"and see what happens...VBAwill do this but also some other programming languages. As far as I know, you cannot avoid this inVBA.