(I am not a programmer and have no idea what I'm doing. This is my first VBA project)
So, I'm trying to hide columns with a zero value. So far, thanks to excelribbon.tips.net, I've managed to get this to work with the following (abbreviated) code
Sub HideColumn1()
If Range(“H5”).Value = 0 Then
Columns(“H”).EntireColumn.Hidden = True
Else
Columns(“H”).EntireColumn.Hidden = False
End If
‘Repeat for everything between H and AG
If Range(“AG5”).Value = 0 Then
Columns(“AG”).EntireColumn.Hidden = True
Else
Columns(“AG”).EntireColumn.Hidden = False
End If
End Sub
There has to be a way to do this that doesn't include 180 lines of repetitive code? Plus when it runs it takes like ten seconds to bump through all the columns individually, and the charts go through some seizure-inducing flashing, and I'd just really rather it did it all at once. I tried changing it to
If Range(“H5:AG5”).Value = 0 Then
Columns(“H:AG”).EntireColumn.Hidden = True
Else
Columns(“H:AG”).EntireColumn.Hidden = False
End If
but that didn't work. I also tried changing it to Range(“H5”,.....”AG5”) and Columns(“H5”,....”AG5”) for the sake of being thorough, even though I really didn't expect it to work.
Can anyone help me please?
Thanks so much everyone!!!
Great first attempt Sylphie! You can use a loop to go through each column and check row 5 of that column. Also, to get rid of the flashing you can turn off ScreenUpdating
, then turn it back on after the code is finished:
Sub HideColumn1()
Dim i As Long
Application.ScreenUpdating = False
For i = 8 To 33 'H through AG
If Cells(5, i).Value = 0 Then
Columns(i).EntireColumn.Hidden = True
Else
Columns(i).EntireColumn.Hidden = False
End If
Next i
Application.ScreenUpdating = True
End Sub
This unhides all the columns, Loops and hides all the correct columns at once. Should be quick and clean.
Sub HideColumn1()
ActiveSheet.Columns("H:AG").Hidden = False
For j = 8 To 33
If ActiveSheet.Cells(5, j).Value = 0 Then
Dim rng As Range
If rng Is Nothing Then
Set rng = ActiveSheet.Cells(5, j)
Else
Set rng = Union(ActiveSheet.Cells(5, j), rng)
End If
End If
Next j
rng.EntireColumn.Hidden = 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.