【问题标题】:Excel VBA - Delete empty columns between two used rangesExcel VBA - 删除两个使用范围之间的空列
【发布时间】:2021-08-17 21:57:36
【问题描述】:

我想根据屏幕截图删除 2 个使用范围之间的所有空列:

但是,这两个使用的范围可能具有不同的列长度,因此空列并不总是 D 到 K 列。

这是我的代码:

Sub MyColumns()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Workbooks.Open ("BOOK2.xlsx")
Workbooks("BOOK2.xlsx").Activate
Workbooks("BOOK2.xlsx").Sheets(1).Activate

Workbooks("BOOK2.xlsx").Sheets(1).Cells(1, 4).Value = "NON-EMPTY"

Dim finalfilledcolumn As Long
finalfilledcolumn = Workbooks("BOOK2.xlsx").Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column

Dim iCol As Long
Dim i As Long

iCol = firstfilledcolumn + 1

'Loop to delete empty columns

For i = 1 To firstfilledcolumn + 1
    Columns(iCol).EntireColumn.Delete
Next i

Workbooks("BOOK2.xlsx").Close SaveChanges:=True

MsgBox "DONE!"

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

但是,空列仍然存在。

请注意,第一个使用范围的最后填充列,Place = "USA",Price = "110" 和 Category = "Mechanical" 可能不会固定在 C 列,但可以转到 D、E 列,等等

非常感谢!

【问题讨论】:

  • 潜在问题:Columns 不符合工作簿/工作表的条件,这意味着它正在隐式处理 ActiveSheet。然后你需要从右到左循环(使用Step -1),如果第一列被填充,我不确定为什么你有For i = 1
  • 啊,我明白了,谢谢指出!

标签: excel vba


【解决方案1】:

请尝试下一个方法:

Sub deleteEmptyColumn()
   Dim sh As Worksheet, lastCol As Long, rngColDel As Range, i As Long
   
   Set sh = ActiveSheet 'use here your necessary sheet, having the workbook open
                        'if not open, you can handle this part...
   lastCol = sh.cells(1, sh.Columns.count).End(xlToLeft).column
   For i = 1 To lastCol
     If WorksheetFunction.CountA(sh.Columns(i)) = 0 Then
        If rngColDel Is Nothing Then
            Set rngColDel = sh.cells(1, i)
        Else
           Set rngColDel = Union(rngColDel, sh.cells(1, i))
        End If
     End If
   Next i
   If Not rngColDel Is Nothing Then rngColDel.EntireColumn.Delete
End Sub

【讨论】:

  • 太棒了,它完全按照预期工作!非常感谢!
【解决方案2】:

试试这个..

Dim rng As Range, i As Long
Set rng = Workbooks("BOOK2.xlsx").Sheets(1).UsedRange
For i = rng.Columns.Count To 1 Step -1
If WorksheetFunction.CountA(rng.Columns(i)) = 0 Then
rng.Columns(i).EntireColumn.Delete
End If
Next i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多