检查范围内的数据types
我试图validation用户select的范围内的所有单元格的数据types是相同的,使用VBAfunction。 我有以下代码(简化),大部分工作:
Dim vTempRange As Variant Dim vCell As Variant vTempRange = DataRange.Value For Each vCell In vTempRange If Len(vCell) > 0 Then 'Use TypeName(vCell) 'Complete validation here End If Next vCell
有时用户可能会select一列百分比,有时候是一列十进制值,有时候会select一个时间值(与date无关)。 VBA似乎将所有这三个看作是Double
,这在技术上并不正确。 问题是,select的格式将被用作最终输出的一部分,所以12:00:00
应该显示为0.50
,而不是0.50
。
我看着一起使用这样的事情:
Dim vCell As Variant For Each vCell In DataRange If Len(vCell) > 0 Then 'Use vCell.NumberFormat 'Complete validation here End If Next vCell
但NumberFormat
不一致。 例如,用户可能具有百分比列举为0%
对比0.000%
或时间为h:m:s
对hh:mm:ss
,所以我认为它很难正确地捕获这个值。
当select一个时间与其他types之一时,有没有一种方法可以在没有用户干预的情况下准确确定? 确定百分比值与0<x<1
十进制值也是很好的,但不是必需的。
我还有其他的select,例如忽略最终输出中的格式(真的不可取)或明确地要求用户识别types(但是这不是我所希望的那样干净和不自动)。
尝试这个。 将其粘贴到模块中。 然后,您可以将其用作工作表公式。
我在我的数据库中有这个代码,这是从这里拿起,我修改它,以满足您的需求。
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
截图
您可以进一步修改它以在Case IsNumeric(c): CellType = "Value"
添加一个IF
子句Case IsNumeric(c): CellType = "Value"
来检查小数,Scientific notation等使用INSTR
声明vCell as Range
,然后做你的检查:
TypeName(vCell.Value)
这将准确地捕捉你的date。
YOu可能需要添加一些if / then逻辑来捕获“百分比”,因为这些是双重types值 – “%”部分仅仅是单元格格式,因此您可能只需检查Right(vCell.NumberFormat,1) = "%"
。