我的目标是确定具有某些价值的工作表中的列。如果一列没有值,它应该被隐藏。我试过它:
Sub HideEmptyCols()
Dim LastCol As Long, i As Long
LastCol = ActiveSheet.UsedRange.Columns.Count
For i = 1 To LastCol
If WorksheetFunction.Count(Columns(i)) = 0 Then
Columns(i).EntireColumn.Hidden = True
End If
Next i
End Sub
如果列没有任何值,但如果列在最后一行中具有值,则它也可以隐藏该列。我正在寻找为什么会发生这种情况以及如何实现目标?
答案 0 :(得分:0)
尝试一下:
Sub ColumnHider()
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
Set r = ActiveSheet.UsedRange
nLastRow = r.Rows.Count + r.Row - 1
nLastColumn = r.Columns.Count + r.Column - 1
For i = 1 To nLastColumn
Set rcol = Cells(1, i).EntireColumn
If wf.CountA(rcol) = 0 Then
rcol.Hidden = True
End If
Next i
End Sub
修改#1:强>
如果标题下方的所有单元格都为空,此版本将隐藏该列:
Sub ColumnHider()
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
Set r = ActiveSheet.UsedRange
nLastRow = r.Rows.Count + r.Row - 1
nLastColumn = r.Columns.Count + r.Column - 1
For i = 1 To nLastColumn
Set rcol = Range(Cells(2, i), Cells(Rows.Count, i))
If wf.CountA(rcol) = 0 Then
rcol.EntireColumn.Hidden = True
End If
Next i
End Sub