选择多个列一次隐藏

时间:2018-10-03 13:46:38

标签: excel vba excel-vba

我正在运行一个报告,其中有多个列,用于比较整个会计年度的数字。例如,7月至8月,8月至9月,等等。不幸的是,当我手动执行此操作时,我必须取消隐藏所有列,并重新隐藏未完成的列。我正在自动执行此报告。此时,我所有可见的列。由于处于会计年度的中间,我的报告将在所需数据的左侧和右侧都包含列。我正在尝试隐藏这些不需要的列。

我创建了一个包含JAN,FEB,MAR等的参考行(第1行),仅供我的代码参考,因为我已经创建了一个检测这些条目的用户窗体。

对于本月我需要的数据,我选择了引用的单元格并将其偏移一个,以获取第一列需要隐藏的列。如何在脚本中选择从选择的列到A列的所有列?以下是我所在位置的代码:

With Worksheets("ACD")
 For counter = 1 To 200
    Set curcell = Worksheets("ACD").Cells(1, counter)
    If curcell.Value = FormMonth Then
    curcell.Offset(0, -1).EntireColumn.Select
    End If
  Next counter
End With

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

以下是根据您的情况如何隐藏多列的示例:

Option Explicit

Public Sub HideMonthColumns()
    Dim workingDate As Date                      'filled in from your form?
    workingDate = #10/1/2018#                    'set for testing here

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("ACD")

    Dim lastCol As Long
    Dim workingCol As Long
    Dim i As Long

    With ws
        lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For i = 1 To lastCol
            If .Cells(1, i) = workingDate Then
                workingCol = i
                Exit For
            End If
        Next i

        '--- hide all the columns to the left and right of the working column
        .Range(.Cells(1, 1), .Cells(1, workingCol - 1)).EntireColumn.Hidden = True

        '--- ... and hide all the columns to the right, checking for the edge
        If (workingCol + 9) < lastCol Then
            .Range(.Cells(1, workingCol + 9), _
                   .Cells(1, lastCol)).EntireColumn.Hidden = True
        End If
    End With
End Sub
相关问题