遍历工作表中的单元格时,如何获取单元格上的格式设置是什么?因为基于此,我想构建一个 SQL 语句来添加单个刻度或不添加到检索的值
4 回答
听起来您需要VarType()函数。 Vartype(Range("A1"))
好的,所以您不想知道单元格的格式设置,而是该值是否为数字。如果可以的话,你可以打电话IsNumeric(Range("A1"))
报价False
吗?
根据您对某些数字作为文本存储在数据库中的评论,您不会通过一个简单的公式来解决这个问题。您不能在构建 SQL 语句时引用这些值吗?
尝试在 VBA 中使用以下内容:
Range("A1").NumberFormat = "0.00" 'Sets cell formatting to numeric with 2 decimals.
Range("A1").Formula = "=Text(6, " & """0.00""" & ")" 'Looks like a number _
' but is really text.
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints False
Range("A1").Value = 6 'Puts number into the cell, which also looks like 6.00
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints True
这应该告诉您该值是真正的文本还是真正的数字,无论单元格的格式属性如何。
关键是 Excel 的固有 IsNumber() 函数比 VBA 函数 IsNumeric 更适用于此目的。IsNumber() 告诉您单元格的值是否为数字,而 IsNumeric 仅告诉您单元格是否已格式化为数值。
我不认为单元格的任何属性可以指示单元格是否实际包含数值,尽管VarType()
可能会有所帮助,但它会变得很棘手,因为 Excel 将允许数字格式的单元格包含字符串,而文本格式的单元格包含数字值,而不覆盖NumberFormat
属性。
在任何情况下,您都可能需要一些独立的测试来确定单元格是否为 IsNumeric(或其他标准)以及它NumberFormat
是否在您可以定义的枚举列表中。
Sub numFormat()
Dim cl As Range
Dim numFormat As String
Dim isNumber As Boolean
For Each cl In Range("A1")
numFormat = cl.NumberFormat
isNumber = IsNumeric(Trim(cl.Value))
Select Case numFormat
Case "General", "0", "0.0", "0.00" ' <--- modify as needed to account for other formats, etc.
If isNumber Then
Debug.Print cl.Address & " formatted as " & numFormat
End If
Case Else
'ignore all other cases
End Select
Next
End Sub
我不认为单元格的格式是重要的。相反,它是数据库中字段的数据类型。如果您在单元格中有字符串“foobar”,并且您创建了一个 INSERT INTO sql 语句,该语句试图将其放入 Long Integer 字段中,那么无论刻度线如何,它都会失败。
相反,如果单元格包含需要进入 VARCHAR 字段的数值(如 100),则需要标记(如“100”)。
如果您使用的是 ADO,请检查 Field 对象的 Type 属性以确定数据类型。使用此列表http://support.microsoft.com/kb/193947查看类型是什么。然后根据字段类型设置SQL语句。