Know the row ID to create a formula with a macro in an excel report

Getting the row ID is quite useful if I know only the column ID, particularly useful to create a formula once I find a specific cell value in order to get the row number.

macro excel
macro excel macro excel

 

When I use the macro ?

When I need to create a formula based on a column and finding a specific value.

 

How to create the macro ?

Read How to create, edit, hide and select a macro in an excel report

 

How to create the button to associate it with the macro ?

Read How to create a button and associated it to a macro in an excel report

 

How is/are the macro(s) ?

Copy the code below and paste it into your macro. You will see my comments in green if exist so follow the help to adapt to your need.

Just to find the row ID for each specific value and no more:


Sub test()
Dim MyVal As String
Dim SrchRng As Long
' change P11 by the value you are searching
MyVal = "P11"
' change D by the column where to search
SrchRng = Cells(Rows.Count, "D").End(xlUp).Row
' if you prefer to define your range, put i.e. Range("D2:D13") and remove the line above and second line of this code
For Each cell In Range("D2:D" & SrchRng)
  If cell.Value = MyVal Then
    ' show a popup with the row ID
    MsgBox cell.Row
  End If
Next cell
End Sub              
              

The same version as above except that I will use the row ID to create a formula:


Sub test()
Dim MyVal As String
Dim SrchRng As Long
' change P11 by the value you are searching
MyVal = "P11"
' change D by the column where to search
SrchRng = Cells(Rows.Count, "D").End(xlUp).Row
' if you prefer to define your range, put i.e. Range("D2:D13") and remove the line above and second line of this code
For Each cell In Range("D2:D" & SrchRng)
  If cell.Value = MyVal Then
    ' example to use the row ID to create a formula by replacing P11 which is =A5+B5
    ' if put for example cell.Row + 1, it means 5 + 1 = 6
    cell.Offset(0) = "=A" & cell.Row & "+B" & cell.Row
  End If
Next cell
End Sub              
              

Interesting Topics