简体   繁体   中英

1004 application defined or object defined error while using specialcells property

Following is the code snippet which helps in understanding the context of the problem. If Not(r is nothing) condition is true then i am getting 1004 error. The peculiar thing is if i run the code in debug mode step by step then error occurs for every 2nd time the condition is satisfied. Kindly help me fix this error. Thanks.

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

I don't think you need the .SpecialCells(xlCellTypeBlanks) piece at all. Since you are just deleting the entire column, you could change the code to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM