ray88’s diary

お仕事で困ったとき用の自分用の覚書

VBA 値の型を判定する(値の型を取得する)varType( ) 関数

ExcelVBA 目次 - ray88’s diary
■値の型を判定するには varType( ) 関数を使用する
■呼び出し元プロシージャ

Sub 型判定()
Dim tempVal As Variant
Dim strVarType As String

tempVal = 1
strVarType = fncVarType(tempVal)
MsgBox strVarType

tempVal = "a"
strVarType = fncVarType(tempVal)
MsgBox strVarType

tempVal = 1.5
strVarType = fncVarType(tempVal)
MsgBox strVarType

End Sub

■値の型判定の部品プロシージャ

Function fncVarType(tempVal As Variant) As String
'----------------------------------------------------
'機 能:引数で受け取った値の型を判定し値の型の文字列を返す
'引数1:判定対象の値
'戻り値:値の型の文字列
'----------------------------------------------------
    Dim intVarType
    Dim strVarType
    
    intVarType = VarType(tempVal)
    
    Select Case intVarType
    Case 0
        strVarType = "Empty"
    Case 1
        strVarType = "Null"
    Case 2
        strVarType = "Integer"
    Case 3
        strVarType = "Long"
    Case 4
        strVarType = "Single"
    Case 5
        strVarType = "Double"
    Case 6
        strVarType = "Currency"
    Case 7
        strVarType = "Date"
    Case 8
        strVarType = "String"
    Case 9
        strVarType = "Object"
    Case 10
        strVarType = "Error"
    Case 11
        strVarType = "Boolean"
    Case 12
        strVarType = "Variant"
    Case 13
        strVarType = "DataObject"
    Case 14
        strVarType = "Decimal"
    Case 17
        strVarType = "Byte"
    Case 18
        strVarType = "Array"
    Case Else
        strVarType = "判定不能"
    End Select
    
    fncVarType = strVarType
    
End Function

出力結果

■参考URL
Office TANAKA - Excel VBA関数[VarType]