VBA CountA错误1004

时间:2018-08-28 16:42:33

标签: excel vba excel-vba

我不断收到错误1004。我不确定如何避免此错误,另外声明我的对象:

Sub DeleteBlank()

    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim ws As Worksheet
    Set ws = wb.Worksheets("Sheet1")
    ws.Activate

    'Delete Blank Columns
    For col = 1 To 4
        If WorksheetFunction.CountA(ws.Columns(i)) = 0 Then
            ws.Columns.Delete
        End If
    Next col


End Sub

1 个答案:

答案 0 :(得分:6)

后退并使用col而不是i。另外,可以用With包装。

Option Explicit
Sub DeleteBlank()

    Dim wb As Workbook
    Set wb = ActiveWorkbook
    Dim col As Long
    Dim ws As Worksheet
    Set ws = wb.Worksheets("Sheet1")

    With ws
        For col = 4 To 1 Step -1
            If WorksheetFunction.CountA(.Columns(col)) = 0 Then
                .Columns(col).Delete
            End If
        Next col
    End With
End Sub