Link to home
Start Free TrialLog in
Avatar of Flora Edwards
Flora EdwardsFlag for Sweden

asked on

VBA change event hide and unhide column

I need help with VBA that is automatic "like worksheet change event" that if all of the rows for column result in zero then hide the column. otherwise unhide all column where one or more rows has value other than zero.

I have attached example file.
Avatar of Roy Cox
Roy Cox
Flag of United Kingdom of Great Britain and Northern Ireland image

There's no attachment.

You need to select the file then click Submit to complete the attachment
Avatar of Flora Edwards

ASKER

oh, my mistake.  attachment is now attached.

as it can be seen column E and Column K all rows for these 0,  so these two columns to be hidden and when they have value again then it should be un-hidden.


thanks.
Book1.xlsm
You may try something like this...
The following code will run on ActiveSheet.
Sub HideUnhideColumns()
Dim lc As Long, lr As Long, i As Long
Dim rng As Range
lr = Cells(Rows.Count, 2).End(xlUp).Row
lc = Cells(1, Columns.Count).End(xlToLeft).Column
Columns.Hidden = False
For i = lc To 3 Step -1
    Set rng = Range(Cells(2, i), Cells(lr, i))
    Columns(i).Hidden = Application.Max(rng) = 0
Next i
End Sub

Open in new window

HideUnhideColumns.xlsm
Thanks Neeraj.  but what i wanted was automatic via the worksheet change event. i am not that good to transform this with the worksheet change event. Can you plz help?
ASKER CERTIFIED SOLUTION
Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this. Make a change to any cell in the sheet and the code is triggered.
HideUnhideColumns.xlsm
@Roy
You placed the code for Selection Change Event not for Change Event and code will be triggered by changing the selection on the sheet and I don't think that's required.
As I said earlier, the Calculate Event is the best approach for this scenario as when values are changed on Sheet2, the formulas on Sheet1 will be recalculated and that should trigger the code to hide and unhide columns on Sheet1 automatically. Also, since there are formulas on Sheet1, changing the cell contents doesn't make much sense here.
I misread, but I agree calculate would be better

I've edited the code
HideUnhideColumns.xlsm
Thanks to both of you.

Neeraj's code nailed it.
You're welcome Flora! Glad it worked as desired.
Thanks for the feedback.
Did my code not work in the last example?
Roy,

Thanks a lot. your code works too. but i used Neeraj's code.
I wondered if it hadn't worked for some reason. Thanks for getting back.
Thanks Roy.

I also marked your answer as helpful.