Search code examples
excelvba

Add row when the first value greater in length is found


I want when the number in column D goes from a 7 digit number to an 11 digit number to add two rows, either below the lower number or above the higher number.

Example:
1656340
1656352
1656389
3156603873
3156690671
3156738131

Column D is in numerical order.

Next when the number jumps from 11 digits to a 17 digits with two hyphens.

Example:
3165694674
3165694674
3168190042
026-1924781-2157120
026-6908033-4106726
028-8563479-8783525

The end result should have a two row gap between these lengths of numbers.

Two of these sets of numbers are randomly generated so will not always ascend in value.

Offset code for another purpose that I can't make work for this:

Sub AddingBreakRows()

Dim R As Range
Set R = Range("I2:I400")
Dim FR As Integer
Dim LR As Integer

FR = 1 ' First Row in R
LR = R.Rows.Count ' Last Row in R

Dim Index As Integer

For Index = LR To FR Step -1
If Not IsEmpty(R(Index)) Then
    R(Index).Offset(1, 0).EntireRow.Insert
End If
Next

End Sub

Solution

  • Try this out:

    Sub AddingBreakRows()
        Const V7DIGITS = "#######"              '7 digit pattern
        Const V11DIGITS = "###########"         '11 digits
        Const V17DIGITS = "###-#######-#######" 'digits with dashes
        
        Dim rng As Range, ws As Worksheet, arr, r As Long, vU, vL, ins As Boolean
        
        Set ws = ThisWorkbook.Worksheets("Data")
        
        Set rng = ws.Range("I2:I" & ws.Cells(rows.count, "I").End(xlUp).row)
        arr = rng.Value 'get all values as array (faster)
        
        'loop over the array of values from the bottom up
        For r = UBound(arr, 1) - 1 To 1 Step -1
            vU = arr(r, 1)       'upper value
            vL = arr(r + 1, 1)   'lower value
            'Does the pattern change here, in one of the ways we're
            '   looking for?
            If (vU Like V7DIGITS And vL Like V11DIGITS) Or _
                  (vU Like V11DIGITS And vL Like V17DIGITS) Then
                rng.Cells(r + 1).Resize(2).EntireRow.Insert
            End If
        Next r
    
    End Sub