Saturday 4 August 2018

Excel automatically adding an extra row with formulas for the inputed number of years


I am looking to build a model. I would like to have an input page where you input the range of years you would like to cover. Depending on the inputted number of years, I want a table (on a different worksheet) to be populated with the existing formulas.


To be more specific, I have a table full of formulas that has a row for each year, ranging from 2005-2014.
My request is as follows:


Is there a way to make an input page that takes in the years and change the table and add/subtract rows based on the inputted range? For example, we change the range on the input page to 2005-2018, then my table will add 4 more rows with the equations.



Answer



The solution
To automate this, use some VBA code that resizes your table after updating the start and end years.


The code
Here is my implementation of this, with the years in "Sheet1" (cells B1 and B2) and the table in "Sheet2". Note that you must add this code to the sheet where the years are in, because the code has to run whenever you change something on that sheet. So in my case, this code is added to "Sheet1".


Private Sub Worksheet_change(ByVal Target As Range)
Dim StartYear, EndYour As Range
Dim UpdateTable As ListObject
Dim NrOfRows, OldNrOfRows As Integer

' Set some ranges
Set StartYear = Worksheets("Sheet1").Cells(1, 2)
Set EndYear = Worksheets("Sheet1").Cells(2, 2)
Set UpdateTable = Worksheets("Sheet2").ListObjects("Table1")

' Check if start or end years have changed
If (Not Intersect(StartYear, Target) Is Nothing) Or (Not Intersect(EndYear, Target) Is Nothing) Then
' Store the new and old number of rows
OldNrOfRows = UpdateTable.ListRows.Count - 1
NrOfRows = EndYear.Value - StartYear.Value + 1

' Resize the table
UpdateTable.Resize UpdateTable.Range.Resize(1 + NrOfRows)

'Delete cells below the table if it gets smaller
If OldNrOfRows > NrOfRows Then
UpdateTable.Range.Offset(NrOfRows + 1, 0).Resize(OldNrOfRows - NrOfRows + 1).Delete
End If
End If
End Sub

Some points of explanation of the code
Some references to Microsoft functions/methods/properties to explain the code:



No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...