如果sum为0,则使用标题查找和删除最后一列

时间:2018-01-26 14:55:34

标签: excel vba excel-vba

我想创建一个宏来查找带有标题的最后一列,并且只有当该列的总和等于零时才删除它。这是我到目前为止所尝试的内容:

Dim LastCol As Long, Dim i As Long

With ThisWorkbook.Sheets("Sheet1")
For i = Range("A1").Column To LastCol Step -1
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    If Application.Sum(Cells(1, i).Resize(LR, 1)) = 0 Then
        Columns(i).EntireColumn.Delete 
    End With
Next i

提前感谢您的关注和帮助

1 个答案:

答案 0 :(得分:2)

尝试这样:

Option Explicit

Public Sub TestMe()

    Dim LastCol As Long, i As Long, LR As Long
    LR = 5
    With ThisWorkbook.Sheets(1)
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For i = LastCol  to .Range("A1").Column Step -1
            If Application.Sum(.Cells(1, i).Resize(LR, 1)) = 0 Then
                .Columns(i).EntireColumn.Delete
            End If
        Next i
    End With

End Sub

这是我改变的:

  • 删除2." Dim here - > Dim LastCol As Long,i As Long;
  • 正确地参考With - End with - 拥有它是一个好习惯,但它应该带给你一些东西 - 因此,你应该在范围之前加一个点 - {{1 }},.Range("A1").Co...Columns(i).Entir...
  • 条件结束时您需要.Cells(1, .Columns;
  • 在顶部添加End If可帮助您在运行代码之前找到类似的错误;
  • 在分配值之前,您正在引用[Option Explicit][1]。因此,它应该在循环之前;
  • 循环从第1列开始,步骤为-1。它需要逆转(10x @Scott Craner);