Search code examples
excelvbaheaderrow

Remove values in a row from columns depending on same value in root column and columns with certain headers


I'm stuck with a Excel VBA problem and I hope someone here can help me with that.

I have a file with prices from different vendors in different columns. There is a root column (in my example file this is the column with the heading "TESLA"). I want the code to delete the prices only in the columns headed "FIAT" and "KIA" if they are in the same row as the price in the "TESLA" column and if they match the price in the "TESLA" column respectively.

So, in my example file, it should delete only the value 36,00 and the value 88,00 in the column "FIAT". In the column "KIA" only the value 56,00 and the value 896,00.

The values in the other columns should be kept, even if they match the value in the "TESLA" column.

Here's what I've got so far:

Sub delete_matches()

    Dim LastRow as long
    Dim LastColumn As Long, i As Long, Position As Long

    With Sheets("Sheet1")
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        For i = LastColumn To 1 Step -1

            Position = InStr(1, .Cells(1, i), "TESLA")

            If Position <> 0 Then
   

  'Here has to happen something..
           


            End If

        Next i

    End With
    
End Sub

Solution

  • First identifying the location of the key columns (TESA,KIA,FIAT), then compare and clean the data.

    Sub delete_matches()
        Dim LastRow As Long
        Dim LastColumn As Long, i As Long
        Dim tCol As Integer, kCol As Integer, fCol As Integer
        With Sheets("Sheet1")
            arr = .UsedRange.Value
            For i = 1 To UBound(arr, 2)
                If Trim(arr(1, i)) = "TESLA" Then tCol = i
                If Trim(arr(1, i)) = "KIA" Then kCol = i
                If Trim(arr(1, i)) = "FIAT" Then fCol = i
            Next i
            If tCol * kCol * fCol = 0 Then
                MsgBox "Can't find key column header"
            Else
                For i = 1 To UBound(arr)
                    If arr(i, kCol) = arr(i, tCol) Then arr(i, kCol) = ""
                    If arr(i, fCol) = arr(i, tCol) Then arr(i, fCol) = ""
                Next i
            End If
            .UsedRange.Value = arr
        End With
    End Sub