删除循环上的运行时错误

时间:2016-05-03 20:02:21

标签: excel vba excel-vba

为什么我为以下代码获取运行时错误类型不匹配的任何想法? if语句似乎存在问题。

运行时错误类型不匹配

Dim rng As Range
Dim cell_search As Range
Dim del As Range
Dim FrRngCount As Range
Dim I As Integer
Dim DatatoData As Worksheet

Set DatatoData = ThisWorkbook.Worksheets("PCA DATA2")

Set FrRngCount = DatatoData.Range("A:A")
I = Application.WorksheetFunction.CountA(FrRngCount)

Set rng = Intersect(DatatoData.Range("CV2:CV" & I), DatatoData.UsedRange)

For Each cell_search In rng
If (cell_search.Value) = "Not in Range" Then
    If del Is Nothing Then
        Set del = cell_search
    Else: Set del = Union(del, cell_search)
    End If
End If
Next cell_search
On Error Resume Next
del.EntireRow.Delete

感谢您的帮助。皮特

2 个答案:

答案 0 :(得分:1)

rng被设置为Nothing吗?试试这个:

Option Explicit

Sub Test()

Dim rng As Range
Dim cell_search As Range
Dim del As Range
Dim FrRngCount As Range
Dim I As Integer
Dim DatatoData As Worksheet

Set DatatoData = ThisWorkbook.Worksheets("PCA DATA2")

Set FrRngCount = DatatoData.Range("A:A")
I = Application.WorksheetFunction.CountA(FrRngCount)    

Set rng = Intersect(DatatoData.Range("CV2:CV" & I), DatatoData.UsedRange)

If Not rng Is Nothing Then

For Each cell_search In rng
    cell_search.Activate
    If cell_search.Value = "Not in Range" Then
        If del Is Nothing Then
            Set del = cell_search
        Else: Set del = Union(del, cell_search)
        End If
    End If
Next cell_search

End If

On Error Resume Next
del.EntireRow.Delete

End Sub

这就是我所拥有的,似乎有效。我添加了cell_search.Active进行调试。您应该尝试一下,看看它在您收到错误时激活的单元格。

答案 1 :(得分:1)

根据您的上述评论(发生错误的地方),似乎无法确定该单元格的.Value。情况就是这样,当公式在该单元格中产生错误时(例如#DIV/0!#NAME?#Ref!)。

所以,我建议您先评估单元格.Value,然后再进行评估:

For Each cell_search In Rng
    If IsError(cell_search.Value) Then
        'What should happen in this case?
    Else
        If (cell_search.Value) = "Not in Range" Then
            If del Is Nothing Then
                Set del = cell_search
            Else: Set del = Union(del, cell_search)
            End If
        End If
    End If
Next cell_search

如果这样可以解决您的问题,请告诉我。