使用specialcells属性时1004应用程序定义或对象定义的错误

时间:2016-03-21 11:40:34

标签: excel excel-vba vba

以下是有助于理解问题背景的代码段。如果Not(r is nothing)条件为真,那么我得到1004错误。奇怪的是,如果我一步一步地在调试模式下运行代码,那么每第二次条件满足就会发生错误。请帮我修复此错误。谢谢。

With wb.Sheets(csht)
    lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    firstCol = 1
    'If IsEmpty(.Cells(1, 1).Value) Then firstCol = .Cells(1, 1).End(xlToRight).Column
End With

'countCol = lastCol - firstCol + 1
On Error Resume Next
If firstCol < lastCol Then
    Set r = wb.Sheets(csht).Range(wb.Sheets(csht).Cells(1, firstCol), wb.Sheets(csht).Cells(1, lastCol)).SpecialCells(xlCellTypeBlanks)
Else
    Set r = wb.Sheets(csht).Range(wb.Sheets(csht).Cells(1, firstCol), wb.Sheets(csht).Cells(1, firstCol)).SpecialCells(xlCellTypeBlanks)
End If
Err.Clear
On Error GoTo 0

If Not (r Is Nothing) Then
    'On Error Resume Next
    With wb.Sheets(csht)
        If firstCol < lastCol Then
            .Range(.Cells(1, firstCol), .Cells(1, lastCol)).SpecialCells(xlCellTypeBlanks).EntireColumn.Delete
        Else
            .Range(.Cells(1, firstCol), .Cells(1, firstCol)).SpecialCells(xlCellTypeBlanks).EntireColumn.Delete
        End If
    End With
'Err.Clear
'On Error GoTo 0
End If

1 个答案:

答案 0 :(得分:0)

我认为你根本不需要.SpecialCells(xlCellTypeBlanks)件。由于您只是删除整个列,因此可以将代码更改为:

With wb.Sheets(csht)
If firstCol < lastCol Then
        .Range(.Cells(1, firstCol), .Cells(1, lastCol)).EntireColumn.Delete
    Else
        .Range(.Cells(1, firstCol), .Cells(1, firstCol)).EntireColumn.Delete
    End If
End With