使用.SpecialCells(xlCellTypeVisible)时如何避免过滤范围上的“类型不匹配”错误?

时间:2018-03-05 14:52:37

标签: excel vba excel-vba

我有一个程序可以过滤几个字段上的数据集,获取过滤数据的最后一行,然后遍历可见行并根据逻辑添加文本。今天,我遇到了一个错误,其中应用了过滤器之后唯一剩余的条目是在第2行。cell.Value行发生错误,并且它引发了“类型不匹配”错误。以下是代码片段:

Dim cell as Range
With ws
    .ShowAllData
    rng_curr.AutoFilter Field:=col_RMDY_TYPE, Criteria1:="Fix"
    rng_curr.AutoFilter Field:=col_RMDY_SUBSTATUS, Criteria1:="In Review"
    rng_curr.AutoFilter Field:=col_RMDY_TARGET_DT, Criteria1:="<=" & Date + 30, Operator:=xlAnd, Criteria2:=">=" & Date
    lrow_temp = .Cells(Cells.Rows.Count, 1).End(xlUp).Row
    If lrow_temp = 1 Then 'if filtered dataset has no entries, then skip adding action items
        'Do Nothing
        Else
        For Each cell In .Range(.Cells(2, col_action_items), .Cells(lrow_temp, col_action_items)).SpecialCells(xlCellTypeVisible)
            cell.Value = "IRM must approve/reject the remedy, as the target date is in " & Round(.Cells(cell.Row, col_RMDY_TARGET_DT).Value - Date) & " days."
            .Cells(cell.Row, col_person_resp).Value = "IRM"
        Next cell
    End If
End With

我已经确认rng_currlrow_temp,并且正确设置了所有col_x个变量。我做了一个Debug.Print cell.address,发现它在A1处设置错误,应该是AN2。我很肯定这个问题是由于过滤后的行位于数据的第2行(正好在标题下方),因为当我将行切割到另一行(即6)时,它没有问题。 / p>

除了添加If lrow_temp = 2支票以外,还有更好的方法可以防止此错误吗?

0 个答案:

没有答案