繁体   English   中英

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

[英]1004 application defined or object defined error while using specialcells property

以下是有助于理解问题背景的代码段。 如果Not(r为空)条件为true,则我收到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

我认为您根本不需要.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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