简体   繁体   中英

Excel VBA: Hiding columns between two given dates

I'm working on a sheet listing days throughout the year. The rows will be populated manually by different users and the purpose is to log these values throughout a whole year. Columns are specific to each day of the year, and therefore a lot of scrolling is required to find a specific range.

What i want to achieve is to have two cells that can be filled with two dates, a start and end date, and when these are entered all the other columns are hidden from view.

I've found a method to hide columns before a given date in one cell, but id like some help to incorporate a way to also hide columns after a given date in another cell. In this case cell E35

The VBA code for the method so far is:

Private Sub Worksheet_Change(ByVal Target As Range)
'Updateby Extendoffice 20160725
    Dim xCell As Range
    If Target.Address <> Range("E34").Address Then Exit Sub
    Application.ScreenUpdating = False
    For Each xCell In Range("H1:NG1")
        xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
    Next
    Application.ScreenUpdating = True
End Sub

A reference picture here: Example

Thank you in advance // R

Following-up on @dgorti answer, in future cases, when you want to monitor the worksheet for multiple ranges, you can use:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("E34:E35")) Is Nothing Then
  ' perform your code hewe

Else
    ' you can put your Exit Sub here
End If

End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
 'Updateby Extendoffice 20160725
  Dim xCell As Range
  If Target.Address <> Range("E34").Address AND Target.Address <> Range("E35").Address Then Exit Sub
  Application.ScreenUpdating = False
  For Each xCell In Range("G1:NG1")
    xCell.EntireColumn.Hidden = (xCell.Value < Range("E34").Value or xCell.Value > Range("E35").Value )
  Next
  Application.ScreenUpdating = True
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