Wednesday, September 3, 2014

Dynamically selecting a row in excel using vba and MATCH function

Problem Statement : In a Resource loading tracker sheet(Planning Bid Managers), I wanted each user to be able to add a new row only above a particular row belonging to that user(so that my totals formula remained intact). However, with the addition of rows, the position of this particular reference row would change. 

What I'm going to do : 
1) first of all, I create form buttons that would be used to insert new rows. (Developer->Insert-> Form Controls-> Button)
Note : If you don't see the Developer tab, you need to go to File-> Excel Options-> Customize Ribbon, and check the "Developer" box. 
2) Then, I assign appropriate macros to perform the insert correctly. 


Execution - How I started : Initially, after inserting the buttons, i began with simply recording macros (View->Macros -> Record Macros), and inserted a row below the desired location. 








So the following macro got created : 
Sub insertrow()
'
' insertrow Macro
' Inserts a new row at selected location
'
    Rows("8:8").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

However, the problem with this is, that it will always insert rows above row 8! This would need to change as new rows get inserted!! So this numbering needs to be dynamic. 

The Solution: 
1) First, I created a small table to keep a track of the person's name using the excel MATCH function in the same worksheet. The MATCH function is used like this - 
=MATCH("Angshuman Majumder",B:B,0)+2
This formula essentially returns the row number where Angshuman is found, and adds 2 to it. (Since I want to add a row 2 rows below the row containing the name of Angshuman). 


Now that I have the number row number where i want the row available, I now modify the macro like this: 

2) '  Instead of  "Rows("8:8").Select" , Get the value of where Angshuman is located thru a variable, then simply select that row!

Sub Angshuman()
'
' Angshuman Macro
    var1 = Worksheets("Planning").Range("Z1").Value
     Rows(var1 & ":" & var1).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

End Sub

Similarly, for the other users, I add macros in turn: 
Sub Mandeep()
'
' Mandeep Macro
'
    var1 = Worksheets("Planning").Range("Z2").Value
    Rows(var1 & ":" & var1).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
End Sub
Sub Suman()
'
' Suman Macro
'
    var1 = Worksheets("Sheet1").Range("Z3").Value
    Rows(var1 & ":" & var1).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
End Sub
Sub Joel()
'
' Joel Macro
'

'
'    Rows("31:31").Select
    var1 = Worksheets("Planning").Range("Z4").Value
     Rows(var1 & ":" & var1).Select

    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

End Sub

And that's how it's done! :-) 

No comments: