2016-11-29 58 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 
相關問題