VBA code to insert an empty column from coolumn I to column HL when the numbering changes in cell $I$4:$H$L4

Anonymous
2024-05-22T22:17:45+00:00

Dear Sir / Madam,

Is there any VBA codes to run in order to execute this task?

Thanks in advance.

Low

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
{count} votes
Answer accepted by question author
  1. Anonymous
    2024-05-23T09:16:01+00:00

    Hi Mr.Low,

    I've understood your requirements is to insert a blank column at the position where the numbering changes.

    Here's a VBA code snippet that traverses from column HL to column I in reverse, inserting a blank column to the right of the current one whenever it detects a change in value. This approach may meet your needs.

    Sub InsertColumnOnNumberChangeRefined() 
    
        Dim ws As Worksheet 
    
        Dim startCol As Long, endCol As Long 
    
        Dim currentValue As Variant 
    
        Dim prevValue As Variant 
    
        Set ws = ActiveSheet 
    
        startCol = 9 
    
        endCol = 220 
    
        For currentCol = endCol To startCol Step -1 
    
            currentValue = ws.Cells(4, currentCol).Value 
    
            If currentCol = endCol Then 
    
                prevValue = currentValue 
    
            Else 
    
                If currentValue <> prevValue Then 
    
                    ws.Columns(currentCol + 1).Insert Shift:=xlToLeft 
    
                    currentCol = currentCol + 1 
    
                End If 
    
                prevValue = currentValue 
    
            End If 
    
        Next currentCol 
    
    End Sub
    

    Please feel free to let me know how it goes.

    Best Regards,

    Jonathan Z - MSFT | Microsoft Community Support Specialist

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2024-05-23T10:35:42+00:00

    Hi Jonathan,

    Yes, the VBA code works perfectly well.

    Many thanks for your quick response.

    Best Regards

    Low

    0 comments No comments