运行不同于我的表单的代码

时间:2016-11-18 20:04:20

标签: excel vba excel-vba

有人可以告知这段代码有什么问题吗?我正在尝试删除任何空白的行或第8列中的“待处理”一词。

如果“修改”表单处于活动状态,则此代码有效,但如果我尝试从其他工作表运行该代码则不行。理想情况下,我希望它在没有实际激活或选择工作表的情况下运行。这可能吗?

谢谢!

Sub pending_blank_delete()

With Sheets("Modifications")
  last_mod_row = .Range("A" & .Rows.Count).End(xlUp).Row
End With

Dim c As Range
Dim SrchRng

    Set SrchRng = Range(Cells(2, 8), Cells(last_mod_row, 8))
    Do
        Set c = SrchRng.find("Pending", LookIn:=xlValues)
        If Not c Is Nothing Then c.EntireRow.Delete
    Loop While Not c Is Nothing

On Error Resume Next
Range(Cells(2, 8), Cells(last_mod_row, 8)).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

1 个答案:

答案 0 :(得分:-1)

这对你有用......

您的范围没有指定哪个工作表,所以我将所有内容都移到了With语句中。当您看到Set SrchRng = Range(.Cells(2, 8), .Cells(last_mod_row, 8))时,.Cells(2, 8)表示Sheets("Modifications").Cells(2, 8)。如果不将其放在With语句中,它将从活动工作表创建范围。不使用With语句的替代方法是Set SrchRng = Range(Sheets("Modifications").Cells(2, 8), Sheets("Modifications").Cells(last_mod_row, 8))

Sub pending_blank_delete()

    Dim c As Range
    Dim SrchRng

With Sheets("Modifications")
    last_mod_row = .Range("A" & .Rows.Count).End(xlUp).Row

    Set SrchRng = Range(.Cells(2, 8), .Cells(last_mod_row, 8))

    Do
        Set c = SrchRng.Find("Pending", LookIn:=xlValues)
        If Not c Is Nothing Then c.EntireRow.Delete
    Loop While Not c Is Nothing

    On Error Resume Next

    Range(.Cells(2, 8), .Cells(last_mod_row, 8)).SpecialCells(xlCellTypeBlanks).EntireRow.Delete

    On Error GoTo 0
End With

End Sub