Excel 如何检查单元格内容的变量类型,区分long和decimal

Excel 如何检查单元格内容的变量类型,区分long和decimal,excel,validation,types,vba,Excel,Validation,Types,Vba,我需要从大量的工作手册中收集sensus数据。 由于我不打算全部阅读它们来检查可能输入的错误数据,我计划突出显示不符合确定数据类型的单元格 为此,我创建了一个列表,其中包含每行的预期数据类型。例如,它们可以是:Long、String或Decimal 我知道存在这样一种模式,用于检测带有UDF的数据类型,这种模式在互联网上随处可见: Public Function CellType(c) Application.Volatile Select Case True C

我需要从大量的工作手册中收集sensus数据。 由于我不打算全部阅读它们来检查可能输入的错误数据,我计划突出显示不符合确定数据类型的单元格

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

我知道存在这样一种模式,用于检测带有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
公共功能单元类型(c)
应用程序。挥发性
选择Case True
Case IsEmpty(c):CellType=“Blank”
Case Application.IsText(c):CellType=“Text”
案例应用程序.IsLogical(c):CellType=“Logical”
Case Application.IsErr(c):CellType=“Error”
案例IsDate(c):CellType=“日期”
案例说明(1,c.文本,“:”)0:CellType=“时间”
案例说明(1,c.文本,“%”)0:CellType=“百分比”
大小写为数字(c):CellType=“Value”
结束选择
端函数

但是,这并不区分
Long
Decimal
数据类型。有没有一种方法可以将其附加到此函数中,或者有没有另一种方法更适合于区分这3种数据类型:
String
Long
Decimal
您只需要测试数值:

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无效?听起来这可以用公式来处理@Rawrplus,单元格(类型)返回:“如果单元格为空,则返回“b”;如果单元格包含文本常量,则返回“l”;对于所有其他单元格,则返回“v”。”根据链接站点。这是如何区分长码和十进制码的?@Qharr,谢谢你的建议,我们将对此进行研究。我注意到的第一件事是它对定义的变量有效,而不是对cell.value?@Luuklag我也注意到了这一点。与
TypeName
相同,我想知道是否所有数字单元格值都存储为
Double
。另一个选项是,您可以尝试检测十进制分隔符。类似于
InStr(c.Value2,Application.International(xlDecimalSeparator))
感谢您的添加。我将首先探讨Qharr建议的vartype路由,因为这将是更干净的代码和更多的本机函数。您使用函数名
CellType
使我认为您打算使用此函数来确定单元格值的数据类型。如果是这种情况,则
VarType
将无法区分整数/十进制类型-所有包含数值的单元格将计算为
VarType 5(vbDouble)
我编辑了我的答案以显示一些比较结果。如果我转到VBA编辑器的直接窗口并键入:
workcell=123
,然后键入
Debug.Print(Vartype(workcell))
我得到的结果是
2
,是一个整数。对值
1.23
而不是
123
执行相同的操作,结果确实得到了
5
。但对我来说,这种区分已经足够准确了。我想知道为什么对于
123
VBA变量和单元格值,您的公式返回
5
。将123放入单元格,然后选择它
foo=activecell.value:?typename(foo)
返回双精度
foo=123:?typename(foo)
返回整数。
Public Function CellVarType(c)
    Application.Volatile
    CellVarType = VarType(c.Value)
End Function