VBA – How to Clear Cell Contents across Multiple Columns if Value not Contained

Issue

I have a macro that creates data in a range of columns starting from column D onwards with n=iCount, e.g. if iCount=4, then the columns are D,E,F,G. Throughout all these columns I would now like to clear cell contents if the cell does not contain a "[AT]".

Optimally, I would also like all the leftover data to be moved to the left, meaning data for each row starts in column D and there are no gaps, but thats of secondary importance.

I have included the prior parts of my macro in case that helps (sorry if it is not clean).

Thanks guys!

Dim Treffer As Worksheet
Dim iCount As Long
Dim i As Long
Set Treffer = ActiveWorkbook.Worksheets("Treffer")

iCount = InputBox(Prompt:="How many columns should be created?")

For i = 1 To iCount
    Treffer.Columns(5).EntireColumn.Insert
    Treffer.Range("E1").Value = "Anmelder" & (iCount + 1) - i
Next i
    
    Treffer.Range("D2:D" & Treffer.Cells(Rows.Count, "D").End(xlUp).Row).TextToColumns , _
        Destination:=Treffer.Range("E2:E" & Treffer.Cells(Rows.Count, "N").End(xlUp).Row), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="" & Chr(10) & "", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True

    Treffer.Columns(4).EntireColumn.Delete

Solution

Seems like you are creating more work continuing to use TextToColumns, and would be better off using Split().
Try something like this:

Sub Tester()

    Dim Treffer As Worksheet
    Dim iCount As Long, i As Long, arr, c As Range, os As Long, v
    
    Set Treffer = ActiveWorkbook.Worksheets("Treffer")
    
    iCount = InputBox(Prompt:="How many columns should be created?")
    For i = 1 To iCount
        Treffer.Columns(5).EntireColumn.Insert
        Treffer.Range("E1").Value = "Anmelder" & (iCount + 1) - i
    Next i
    
    For Each c In Treffer.Range("D2:D" & Treffer.Cells(Rows.Count, "D").End(xlUp).Row).Cells
        If Len(c.Value) > 0 Then                   'cell has a value?
            arr = Split(c.Value, vbLf)             'split value on Chr(10)
            os = 1                                 'reset column offset
            For Each v In arr                      'loop over array values
                If InStr(1, v, "[AT]") > 0 Then    'value contains "[AT]" ?
                    c.Offset(0, os).Value = v      'populate in offset column
                    os = os + 1                    'next column to right
                    If os > iCount Then Exit For   'stop if reached column count limit
                End If 'value has [AT]
            Next v
        End If         'any cell value
    Next c
    
    Treffer.Columns(4).EntireColumn.Delete

End Sub

Answered By – Tim Williams

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.