Excel宏:检查列时如何忽略标题行

时间:2012-12-11 23:31:19

标签: excel excel-vba vba

HideEmptyColumns()宏会隐藏所有没有任何数据的列。如何修改它以忽略标题行(第1行)?

Sub HideEmptyColumns()
  Dim Col As Range
  For Each Col In ActiveSheet.UsedRange.Columns
     Col.EntireColumn.Hidden = RangeIsEmpty(Col)
  Next Col
End Sub

Function RangeIsEmpty(R As Range) As Boolean
  Dim Cell As Range
  RangeIsEmpty = True
  For Each Cell In R.Cells
     If Cell.Value <> "" Then
        RangeIsEmpty = False
        Exit For
     End If
  Next Cell
End Function

1 个答案:

答案 0 :(得分:3)

只需查看其上的行

即可
Sub HideEmptyColumns()
  Dim Col As Range
  For Each Col In ActiveSheet.UsedRange.Columns
     Col.EntireColumn.Hidden = RangeIsEmpty(Col)
  Next Col
End Sub

Function RangeIsEmpty(R As Range) As Boolean
  Dim Cell As Range
  RangeIsEmpty = True
  For Each Cell In R.Cells
     'are we not on the first row (header row)
     If Cell.Row <> 1 Then
        If Cell.Value <> "" Then
           RangeIsEmpty = False
           Exit For
        End If
     End If
  Next Cell
End Function