VBA to run when either of two cells changed by user

asad

Well-known Member
Joined
Sep 9, 2008
Messages
1,434
Hello VBA Gurus,

Yet again I unsuccessfully tried to write VBA code. Can you guys please let me know what is wrong with this code. I am simply trying to hide all columns in range E3 to PZ3 if the dates in these are less than the date in C1 or greater than the date in D1.
VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCell As Range
    
        If Target.Address <> Range("C1").Address Or Target.Address <> Range("D1") Then Exit Sub
            Application.ScreenUpdating = False
                For Each xCell In Range("E3:PZ3")
                    If xCell < Range("C1") Or xCell > Range("D1") Then
                    xCell.EntireColumn.Hidden = True
                    End If
                Next
    Application.ScreenUpdating = True
End Sub
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
Are both C1 and D1 populated, as the code will fail if one is blank.
Try
VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCell As Range
    Application.ScreenUpdating = False
   If Intersect(Target, Range("C1:D1")) Is Nothing Then Exit Sub
   If Range("C1") = "" Or Range("D1") = "" Then Exit Sub
                For Each xCell In Range("E3:PZ3")
                    If xCell < Range("C1") Or xCell > Range("D1") Then
                    xCell.EntireColumn.Hidden = True
                    End If
                Next
    Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,908
Messages
6,122,186
Members
449,071
Latest member
cdnMech

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top