Insert row above if cell in column B partially contains 2 (e.g. A2,B2,C2...)

VictoriaExcel

New Member
Joined
Nov 15, 2018
Messages
14
I need a macro that inserts a row above each cell in column B that partially contains 2 e.g. A2, B2, C2 - W2.

Many thanks in advance!
 

Some videos you may like

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).

jmacleary

Well-known Member
Joined
Oct 5, 2015
Messages
945
Office Version
2007
Platform
Windows
Hi there. This code will do it:
Code:
Sub Macro1()
'
' Macro1 Macro
'

'
With ActiveSheet
    lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
    For rownum = lastrow To 1 Step -1
    If InStr(.Range("B" & Format(rownum)).Text, "2") > 0 Then
        .Rows(rownum).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    End If
    Next rownum
End With
End Sub
 

VictoriaExcel

New Member
Joined
Nov 15, 2018
Messages
14
Hello,

Thank you for your help with this! The macro almost works but unfortunately it inserts rows above A12, B12, C12 etc as well as the intended A2, B2, C2.

Can it work around this with an exception?

Many thanks,

Victoria
 

jmacleary

Well-known Member
Joined
Oct 5, 2015
Messages
945
Office Version
2007
Platform
Windows
Hi Victoria

OK, so if I understand it, you only want blanks above rows in column B which only contain 2 - so A12, C21, D22 etc would not want a blank row. If thats the case, try this:
Code:
Function GetNumeric(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef)
For i = 1 To StringLength
If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1)
Next i
GetNumeric = Result
End Function
Sub Macro1()
'
' Macro1 Macro
'

'
With ActiveSheet
    lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
    For rownum = lastrow To 1 Step -1
    If GetNumeric(.Range("B" & rownum).Text) = 2 Then
        .Rows(rownum).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    End If
    Next rownum
End With
End Sub
I must admit to lifting the getnumeric code from another forum post - what it does is extract digits only from the entire cell. Hope this helps.

John
 
Last edited:

Watch MrExcel Video

Forum statistics

Threads
1,099,328
Messages
5,467,970
Members
406,561
Latest member
Grappledog

This Week's Hot Topics

Top