VBA无法识别空单元格,数字单元格和文本?

时间:2018-01-31 14:44:52

标签: excel vba excel-vba

我正在尝试在VBA中读取单元格并根据它们的内容执行某些操作。但是,VBA无法准确确定单元格的内容是空白,数字还是文本。它会认为只有一个' 1'在它们中是空白的,带有文本的单元格是空白的。如果它有所不同,我会在运行时关闭所有屏幕更新等。

请参阅以下代码:

Function IsNumber(ByRef expression As Variant) As Boolean    
    IsNumber = Not IsEmpty(expression) And IsNumeric(expression)    
End Function

Function IsText(ByRef expression As Variant) As Boolean    
    IsText = Not IsEmpty(expression) And Not IsNumeric(expression)    
End Function

Sub RA()
    Dim cell As Range    
    With ActiveWorkbook.Worksheets("Sheet1")
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set r = Worksheets("Sheet1").Range(Cells(3, 3), Cells(lastrow, lastCol - 1))
     End With

    For i = 3 To lastrow
        Set c = Cells(i, 3)
        Select Case True
            Case S1_Func(c)
        End Select
    Next i
End Sub

Function S1_Func(c As Variant)
    Dim SR As Worksheet
    Set SR = Worksheets("Financials")
    Dim c2 As Range    
    Set c2 = c.Offset(0, 1)

    If IsNumber(c2.Value2) Then
        Select Case True
            Case SR.Cells(i, 5).Value2 = "LY"
        End Select
    ElseIf IsText(c2.Value2) Then
        Cells(i, 72).Value2 = "Incorrect"
    End If
End sub

1 个答案:

答案 0 :(得分:0)

经过以下讨论后更新。

Function IsNumber(ByRef expression As Variant) As Boolean    
    IsNumber = expression <> "" And IsNumeric(expression)    
End Function

Function IsText(ByRef expression As Variant) As Boolean    
    IsText = expression <> "" And Not IsNumeric(expression)    
End Function

原帖:

您的代码中存在一些混合问题。 Select声明有几个问题,非常具有误导性。在这种情况下,您无法使用SelectIf是您的最佳选择。尝试这样的事情:

Sub Example()
    If Len(Value) = 0 Then
        'Empty
    ElseIf IsNumeric(Value) Then
        'Numeric
    Else
        'Alphanumeric
    End If
End Sub