Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

macro for Hide rows in excel 2010

Tags:

excel

hide

vba

row

I'm kinda new to programming in VBA. I read some stuff on the internet but I couldnt find what I need or couldnt get it working. My problem:

in worksheet 'sheet 1' in cell B6 a value is given for how many years a project will be exploited.

in worksheets 'sheet 2' and 'sheet 3' i made a spreadsheet for 50 years ( year 1 to year 50; row 7 to row 56).

in cell b6 in 'sheet 1' i want to enter a value between 1 and 50. when the value is 49 i want to hide row 56 in 'sheet2' and 'sheet 3'. when the value is 48 i want to hide rows 55:56 in 'sheet2' and 'sheet 3', and so on. this is what i got so far but i cant get it to work automaticly when i change the value in cell B6:

Sub test1()
    If Range("sheet1!B6") = 50 Then
    Rows("52:55").EntireRow.Hidden = False
    Else
    If Range("sheet1!B6") = 49 Then
    Rows("55").EntireRow.Hidden = True
    Else
    If Range("sheet1!B6") = 48 Then
    Rows("54:55").EntireRow.Hidden = True
    
    End If: End If: End If:
    
    End Sub

i hope someone can help me with my problem.

Thank you

like image 364
Benno Houben Avatar asked Jul 04 '11 22:07

Benno Houben


1 Answers

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

like image 166
lionz Avatar answered Sep 21 '22 10:09

lionz