【问题标题】:Delete Blank or zero columns in a range删除区域中的空白或零列
【发布时间】:2017-06-29 03:33:18
【问题描述】:

这就是我需要的:范围说列 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

【问题讨论】:

  • 向后迭代:For i = LastColumn to 1 step -1
  • 除了创建和解析字符串,为什么不直接使用If i >=11 And i <=13 then
  • @ScottCraner 那肯定行得通,尽管在实践中我发现使用范围对象并通过联合向它添加范围,然后在最后调用删除总是更快。你会同意还是我的明显疏忽?
  • @Zerk 不,一次删除总是比多次删除要快,但由于 OP 最多只删除三列,因此差异可能不值得。

标签: vba excel


【解决方案1】:

如果我对您的理解正确,则以下内容应删除“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多