首页 > 解决方案 > 如何检查单元格内容的变量类型,区分长和小数

问题描述

我有需要从大量工作簿中汇总的感觉数据。由于我不打算阅读所有这些以检查可能错误输入的数据,因此我计划突出显示不符合确定数据类型的单元格。

为此,我创建了一个列表,其中包含每一行的预期数据类型。例如,它们可以是LongStringDecimal

我知道存在这种用于检测带有 UDF 的数据类型的模式,该模式在互联网上随处可见:

Public Function CellType(c)
    Application.Volatile
    Select Case True
        Case IsEmpty(c): CellType = "Blank"
        Case Application.IsText(c): CellType = "Text"
        Case Application.IsLogical(c): CellType = "Logical"
        Case Application.IsErr(c): CellType = "Error"
        Case IsDate(c): CellType = "Date"
        Case InStr(1, c.Text, ":") <> 0: CellType = "Time"
        Case InStr(1, c.Text, "%") <> 0: CellType = "Percentage"
        Case IsNumeric(c): CellType = "Value"
    End Select
End Function

但是,这不区分数据类型LongDecimal数据类型。有没有办法将它附加到这个函数,或者有另一种更适合区分这 3 种数据类型的方法StringLongDecimal.

标签: excelvalidationtypesvba

解决方案


您只需要测试数值:

Public Function CellType(c)
    Application.Volatile
    Select Case True
        Case IsEmpty(c): CellType = "Blank"
        Case Application.IsText(c): CellType = "Text"
        Case Application.IsLogical(c): CellType = "Logical"
        Case Application.IsErr(c): CellType = "Error"
        Case IsDate(c): CellType = "Date"
        Case InStr(1, c.Text, ":") <> 0: CellType = "Time"
        Case InStr(1, c.Text, "%") <> 0: CellType = "Percentage"
        Case IsNumeric(c)
            If c = Int(c) Then
                CellType = "Integer"
            Else
                CellType = "Decimal"
            End If
    End Select
End Function

编辑:

与一些替代方法相比,此函数返回的内容如下:

在此处输入图像描述

使用此功能,测试varType

Public Function CellVarType(c)
    Application.Volatile
    CellVarType = VarType(c.Value)
End Function

推荐阅读