View Single Post
 
Old 05-04-2012, 07:16 AM
Peter Wienand Peter Wienand is offline Windows 7 64bit Office 2010 32bit
Novice
 
Join Date: May 2012
Posts: 15
Peter Wienand is on a distinguished road
Default

Yes, this isn't too hard.

A good way to code up something like this is to start by recording a macro where you hide rows and update the chart data and then modify the resulting code to meet your purpose. Looking a recorded code is usually the easiest way to work out how to reference the objects that you are interested in and to identify the properties/methods of these objects that you should be calling to achieve your desired outcome.

Between the code that you record and the sample code below hopefully you will be able to craft a suitable solution!

Something like this would be able to hide the rows based upon the retirement age...

Code:
 
Public Sub hideRows()
'Declare variables Dim i As Integer 'For iterating through rows Dim totalRows As Integer 'Stores row number of bottom row on worksheet Dim retireAge As Integer 'Stores retirement age 'Initialise variables retireAge = Sheets("Sheet1").Range("B3").Value totalRows = Sheets("Sheet1").UsedRange.Rows.Count 'Set to index of last row in UsedRange totalRows = Sheets("Sheet1").UsedRange.Rows(totalRows).Row 'Get row number of last row in UsedRange 'Loop through rows For i = 1 To totalRows
'If any rows below retirement age are hidden, then unhide them If i <= retireAge And Sheets("Sheet1").Rows(i).EntireRow.Hidden = True Then
Sheets("Sheet1").Rows(i).EntireRow.Hidden = False
'If any rows above retirement age are shown, then hide them ElseIf i > retireAge And Sheets("Sheet1").Rows(i).EntireRow.Hidden = False Then
Sheets("Sheet1").Rows(i).EntireRow.Hidden = True
End If
Next i
End Sub
The code for updating the chart will depend on what type of chart you are using.

Code:
 
Public Sub updateGraph()
'Declare variables Dim retireAge As String 'Stores retirement age 'Initialise variables retireAge = Sheets("Sheet1").Range("B3").Value 'Set source range for chart 'If there is only one chart on Sheet1 and this is the chart we want to update then... Sheets("Sheet1").ChartObjects(1).Chart.SetSourceData Source:=Sheets("Sheet1").Range("A3:A" + retireAge) 'If chart has been added as its own tab in the workbook then... Charts("Chart1").SetSourceData Source:=Sheets("Sheet1").Range("A3:A" + retireAge)
End Sub
If you want to get fancy, you could make the updates automatically apply whenever the retirement age is updated using the relevant worksheet's change event... (note that this code, as per the examples above, assumes that the retirement age is located in cell B3 of the worksheet)

Code:
 
Private Sub Worksheet_Change(ByVal Target As Range)
'This subroutine is called EVERY TIME a change is made to the worksheet, so it is important to ensure that 'our macros are only trigger when the retirement age is changed If Target.Address = "$B$3" Then
Call hideRows Call updateGraph
End If
End Sub
Reply With Quote