是否有像IsNumeric这样的VBA函数,但对于Text?当涉及范围时,IsText和IsEmpty无法正常工作

时间:2019-03-06 19:51:52

标签: excel vba

问题:需要能够检查范围或单个单元格以查看是否为空白。

我用对号替换任何文本的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
' If the range (as defined in the next line) is changed to anything but a blank, replace it with a check mark.

If Not Intersect(Range(Target.Address), Range("C6:C60")) Is Nothing Then
    On Error GoTo ErrorOut
    Application.EnableEvents = False
    If Application.WorksheetFunction.IsText(Range(Target.Address)) Then
        Range(Target.Address).Value = "P"
        Range(Target.Address).Font.Name = "Wingdings 2"
    End If
    Application.EnableEvents = True
End If
Exit Sub

ErrorOut:
Debug.Print "Error"
Application.EnableEvents = True
End Sub

有效。但是,如果用户选择多个单元并删除它们,则错误处理将接管。没问题,因为它有效,但是必须有更好的方法。

当我想使用If IsNumeric(Range(Target.Address)) Then检查数字时,我已经成功地做到了。如果一堆单元格被一次删除,它可以正常工作。但是IsTextIsEmpty的行为似乎与IsNumeric并不完全一样,一次删除一堆单元格会产生错误。

1 个答案:

答案 0 :(得分:1)

考虑:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, r As Range, rIntersect As Range
    Dim wf As WorksheetFunction

    Set rng = Range("C6:C60")
    Set rIntersect = Intersect(Target, rng)
    Set wf = Application.WorksheetFunction

    If rIntersect Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In rIntersect
            If wf.CountA(r) = 1 Then
                r.Value = "p"
                r.Font.Name = "Wingdings 2"
            End If
        Next r
    Application.EnableEvents = True

End Sub

我们一次循环Intersection一个单元格。顺便说一下,我使用:

r.Value = "a"
r.Font.Name = "Marlett"