我正在一个项目上,我需要一个程序来删除A到F列和J列中的空列(标题除外)。我希望它遍历Range("A10:F10000")
和Range("J:J")
,然后从单元格A10,B10等中删除该列,然后向下移动,然后将剩余数据向左移动。我正在使用它,它会影响整个工作表,而不只是一个范围:
ecl = Sheet1.Cells.SpecialCells(xlCellTypeLastCell).Column
For cl = ecl To 1 Step -1
cnt = Application.WorksheetFunction.CountA(Sheet1.Columns(cl))
If cnt = 1 Then
Sheet1.Columns(cl).Delete
End If
Next
我通常可以使用公式,并且对VBA不太熟悉,但是对于此项目,它必须是一个宏。我希望这是有道理的,并且不胜感激!
答案 0 :(得分:1)
您可以使用:
Dim cl As Range, colsToDelete As Range
With ActiveSheet 'reference wanted sheet
Set colsToDelete = .UsedRange.Columns(.UsedRange.Columns.Count).Offset(, 1).Resize(1, 1) ' initialize 'colsToDelete' to a "dummy" range certainly out of relevant one
With Intersect(.Range("A10:J" & .UsedRange.Rows(.UsedRange.Rows.Count).Row), .Range("A:F, J:J")) ' reference referenced sheet range in column A to F and G form row 10 down to referenced sheet last not empty cell row
For Each cl In .Columns ' lop through referenced range columns
If Application.WorksheetFunction.CountA(cl) = 1 Then Set colsToDelete = Union(colsToDelete, cl) 'if current column is empty (i.e. only header in row 10) then add it to the colsToDelete range
Next
Set colsToDelete = Intersect(colsToDelete, .Cells) ' get rid of the "dummmy" range
End With
End With
If Not colsToDelete Is Nothing Then colsToDelete.EntireColumn.Delete ' if any range to delete, do it!