excelvbainsert

Excel VBA Insert Column when Value Changes and add formula


Through VBA I want to compare hotel rates between operators.

the Top image is how it is pulled the bottom image is the final output desired

I want to Insert a column each time the HOTEL changes.

Then in that newly added Column, insert the formula for the MIN of each hotel rates.

enter image description here

enter image description here

current code so far but this doesnt work when Z is not operating a hotel

Sub Insert()
'
Dim x As Long, rng As Range

Set rng = Range("B2:DD2")

For Each cell In rng
    If cell = "Z" Then
        cell.EntireColumn.Offset(0, 1).Insert (xlShiftToRight)
    End If
Next cell

End Sub

Solution

  • Option Explicit
    
    Sub InsertMin()
        
        Dim ws As Worksheet
        Dim rng As Range, hotel As String, f As String
        Dim lastRow As Long, lastCol As Long
        Dim c As Long, n As Long, i As Long
        
        Set ws = ActiveSheet
        With ws
            lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
            lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
           
            ' insert columns
            For c = lastCol To 2 Step -1
               If .Cells(1, c) <> hotel Then
                   hotel = .Cells(1, c)
                  .Columns(c + 1).Insert
                  .Cells(1, c + 1) = hotel
                  .Cells(3, c + 1) = "MINRATE"
                  ' insert blank column
                  .Columns(c + 2).Insert
                  
                  i = i + 1
               End If
            Next
            
            ' add MIN formulas
            n = 0
            For c = 2 To lastCol + i * 2
                
                If .Cells(3, c) = "MINRATE" Then
                    f = "=MIN(RC[-" & n & "]:RC[-1])"
                    Set rng = .Cells(4, c).Resize(lastRow - 3)
                    rng.FormulaR1C1 = f
                    n = 0
                ElseIf .Cells(1, c) <> "" Then
                    n = n + 1
                End If
    
            Next
        End With
        MsgBox i & " columns inserted", vbInformation
           
    End Sub