TypeName vs VarType

时间:2017-10-05 07:43:15

标签: vba types

我想查看Variant的类型。可以使用TypeNameVarType执行此操作。我想使用VarType更有效,因为它不涉及字符串比较,只是数字比较。是否有理由选择TypeName

Public Sub testType()
    Dim b() As Double
    Dim a As Variant
    a = b

    Debug.Print TypeName(a) = "Double()" 'True
    Debug.Print VarType(a) = vbArray + vbDouble 'True
End Sub

2 个答案:

答案 0 :(得分:6)

我的推荐

VarType用于VbVarType枚举所涵盖的内置类型。将TypeName用于其他类型。我将在下面详细解释这一建议。

<强>性能

性能差异很可能是微不足道的,特别是如果您使用VBA编写数据库应用程序。

<强> VarType函数

VarType的一大优势是它不使用魔术字符串:如果拼错vbDouble,则会出现编译时错误(假设您使用Option Explicit,您应该使用"Double()" )。如果你拼错TypeName,你的代码就会默默地做错事。

<强>类型名

VbVarType的优点是它也适用于Dim b As New Collection Dim a As Variant Set a = b Debug.Print VarType(a) ' Prints just the generic vbObject constant Debug.Print TypeName(a) ' Prints "Collection" 枚举未涵盖的类型:

VarType

<强>陷阱

请注意,如果变量包含具有默认属性的对象,则vbObject将返回默认属性中包含的值的类型,而不是TempVars("x") = 123 Dim a As Variant Set a = TempVars("x") Debug.Print VarType(a) ' Prints vbInteger, the type of a.Value's current content. ' (Value is TempVar's default property) Debug.Print TypeName(a) ' Prints "TempVar" 。以下是使用MS Access VBA的TempVar类的示例:

ScrollView

答案 1 :(得分:1)

TypeName 与对象(例如范围或表格)一起使用时似乎更具体。

例如使用 LastRow 函数,您希望从其他 vba 函数以及工作表单元格调用该函数。当从另一个单元格传递工作表名称时,它会将其定向为范围,但根据 VarType,它是一个字符串(而不是范围/对象)。

Public Function LastRow(ByVal sht As Variant, Optional ByVal colLetter As String = "NoColGiven") As Long
    Dim aSheet As Worksheet
    Select Case TypeName(sht)
        Case "Worksheet" 'VarType 9 (vbObject)
            'call from vba -> LastRow(Sheets(1))
            Set aSheet = sht
        Case "String" 'VarType 8 (vbString)
            'call from vba/ws function -> LastRow("Sheets1")
            Set aSheet = Sheets(sht)
        Case "Range" 'VarType 8 (vbString)
            'call from ws function -> LastRow(A1) where A1 has textvalue "Sheet1"
            Set aSheet = Sheets(sht.Value)
    End Select

    If colLetter = "NoColGiven" Then
        LastRow = aSheet.UsedRange.Rows(aSheet.UsedRange.Rows.Count).row 'last row in whole sheet
    Else
        LastRow = aSheet.Cells(aSheet.Rows.Count, colLetter).End(xlUp).row 'last row in specified column of sheet
    End If
End Function