删除范围中的空白列或零列

时间:2017-02-10 17:26:06

标签: excel vba excel-vba

这就是我需要的:范围说列F:F,G:G,K:K。如果单元格为零,则删除整个列,或仅为这些特定列删除整个列。如果其中有任何其他值,则不执行任何操作。

以下是我现在使用的内容。但是这会删除不应删除的其他列。

LastRow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
LastColumn = Sheets("Sheet1").Cells(9, Columns.Count).End(xlToLeft).Column
lastcol_name_1 = Replace(Cells(1, LastColumn).Address(False, False), "1", "") 

'to find letter of last column

With Sheets("Sheet1")         
    For i = 1 To LastColumn
        lastcol_name_1 = Replace(Cells(1, i).Address(False, False), "1", "") 'to find letter of last column
        If(lastcol_name_1=“K” or lastcol_name_1=”L” or lastcol_name_1=”M”) then ‘write the column name here
            If Evaluate("sum(countif(" & .Range(.Cells(10, i), _
                .Cells(LastRow, i)).Address & ",{"""",0}))") = LastRow - 10 + 1 Then _
                .Columns(i).Delete
        Endif
    Next i

1 个答案:

答案 0 :(得分:0)

如果我正确理解您,以下内容应删除列" F"," G"和" K"如果它们是空的并将剩余的列向左移动 - 假设你想在这里做什么。我尽可能多地留下了你自己的代码:

Sub main():

  LastColumn = Sheets("Sheet1").Cells(9, Columns.Count).End(xlToLeft).Column
  lastcol_name_1 = Replace(Cells(1, LastColumn).Address(False, False), "1", "")

  For i = LastColumn To 1 Step -1
    lastcol_name_1 = Replace(Cells(1, i).Address(False, False), "1", "")
    If (lastcol_name_1 = "F" Or lastcol_name_1 = "G" Or lastcol_name_1 = "K") Then
      If Application.CountA(Columns(i).EntireColumn) = 0 Then
        Columns(i).Delete Shift:=xlToLeft
      End If
    End If
  Next i

End Sub