VBA Excel-无法在重叠的选择上使用该命令

时间:2019-04-18 21:59:24

标签: excel vba

我的代码似乎可以工作,但是突出显示了我的最后一行代码,并说:“运行时错误'1004':不能在重叠的选择上使用该命令。”

我已经尝试了一些在线发现的各种更改,但似乎无法解决该错误。

Sub Delete_EEE()

Dim Wrds As Variant, Gwrds As Variant, i As Long, Fnd As Range, fAdr As String

Gwrds = Array("jan", "m123", "06014", "06015", "06016", "t49", "m39", "cwr", "rnc", "d55", "rer", "rlr", "rwr", "M55", "5962")

Wrds = Array("ohm", "resistor", "semiconductor", "MCKT", "MICKT", "microcircuit", "inductor", "xfmr", "eeprom", "oscillator")

'Application.ScreenUpdating = False

For i = LBound(Gwrds) To UBound(Gwrds)
    Set Fnd = Range("G:G").Find(Gwrds(i), , , xlPart, , , False)
    If Not Fnd Is Nothing Then
        fAdr = Fnd.Address
        Fnd.Value = "#N/A"
        Do
            Set Fnd = Range("G:G").FindNext(Fnd)
            If Fnd Is Nothing Then Exit Do
            If Fnd.Address = fAdr Then Exit Do
            Fnd.Value = "#N/A"
        Loop
    End If
Next i

For i = LBound(Wrds) To UBound(Wrds)
    Set Fnd = Range("E:E").Find(Wrds(i), , , xlPart, , , False)
    If Not Fnd Is Nothing Then
        fAdr = Fnd.Address
        Fnd.Value = "#N/A"
        Do
            Set Fnd = Range("E:E").FindNext(Fnd)
            If Fnd Is Nothing Then Exit Do
            If Fnd.Address = fAdr Then Exit Do
            Fnd.Value = "#N/A"
        Loop
    End If
    Set Fnd = Range("I:I").Find(Wrds(i), , , xlPart, , , False)
    If Not Fnd Is Nothing Then
        fAdr = Fnd.Address
        Fnd.Value = "#N/A"
        Do
            Set Fnd = Range("I:I").FindNext(Fnd)
            If Fnd Is Nothing Then Exit Do
            If Fnd.Address = fAdr Then Exit Do
            Fnd.Value = "#N/A"
        Loop
    End If
Next i

Range("E:I").SpecialCells(xlCellTypeConstants, xlErrors).EntireRow.Delete

'Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:1)

您遇到的问题是Range.Areas。就您而言,.SpecialCells函数创建了多个Areas,并且其中一个或多个区域重叠。例如,如果您的任何行在一个以上的列中都有错误,那么您将有重叠的区域(即,两个或多个区域都包含同一行)。您不能在重叠区域上运行Delete方法。

有很多方法可以解决此问题,但是一个简单的方法就是Intersect将工作表的单元格与您的范围一起使用。这种强制Excel删除重叠的部分。

所以您的最后一行可能只是:

Intersect(Sheet1.Cells, Sheet1.Range("E:I").SpecialCells(xlCellTypeConstants, xlErrors).EntireRow).Delete

您会注意到我已经通过使用工作表对象限定了范围。您可能要遵循该协议,因为它可以防止代码在不正确的工作表上意外运行。

顺便说一句,如果您只对“ E”和“ I”列感兴趣,则范围定义如下:

Intersect(Sheet1.Cells, Sheet1.Range("E:E,I:I").SpecialCells(xlCellTypeConstants, xlErrors).EntireRow).Delete

答案 1 :(得分:1)

当尝试删除具有隐藏列的整行时,我遇到了此错误。在尝试Entirerow.delete之前,我让程序取消隐藏列,这对我有用。