简体   繁体   中英

Selecting Multiple Columns to hide at once

I am running a report in which has multiple columns that compares numbers throughout the fiscal year. For example, July to August, August to September, etc. Unfortunately, when I do this manually, I have to unhide all columns and rehide columns not used to complete. I am automating this report. At this moment, I have all of the columns visible. Due to being in middle of the fiscal year, my report will have columns on both the left and right sides of the needed data. I am trying to have these unneeded columns hidden.

I have created a reference row (row 1) with JAN, FEB, MAR, etc for reference purposes only for my code as I have created a userform that detects these entries.

For the data I need this month, I have selected the referenced cell and offset it by one to get the first column selected that I will need hidden. How would I select all of the columns from my selected column to the column A in my script? Below is the code of where I am:

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

Thanks for you help!

Here's an example on how to hide multiple columns, based on your situation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM