Excel - loop through and empty cells where needed

Costas

Administrator
Staff member
in the following code, compare the 3rd column on each row, if is the same as the previous one, then empty the cells needed.
Useful when export raw data by database when making a breakdown of records..

JavaScript:
Sub Button1_Click()
 
    Application.ScreenUpdating = False
 
    Dim ws As Worksheet
    Dim r As Range
    Dim iRow As Long
 
    Set ws = ThisWorkbook.Worksheets("Export Worksheet")
    Set r = ws.Range("A1:K16376")
 
 
    Dim prevValue As String
    prevValue = "00"
 
    For iRow = 1 To r.Rows.Count
 
       If (r.Cells(iRow, 3) = prevValue) Then
        prevValue = r.Cells(iRow, 3)
 
        r.Cells(iRow, 1).Value = ""
        r.Cells(iRow, 2).Value = ""
        r.Cells(iRow, 3).Value = ""
        r.Cells(iRow, 4).Value = ""
        r.Cells(iRow, 5).Value = ""
        r.Cells(iRow, 6).Value = ""
        r.Cells(iRow, 9).Value = ""
        r.Cells(iRow, 10).Value = ""
        r.Cells(iRow, 11).Value = ""
 
       Else
        prevValue = r.Cells(iRow, 3)
 
       End If
 
 
 
    Next iRow
 
    Application.ScreenUpdating = True
End Sub


or for speed use an empty string array and pass it to a row range

JavaScript:
Sub Button1_Click()
.
.
   Dim bl(6) As String
.
.
       If (r.Cells(iRow, 3) = prevValue) Then
            prevValue = r.Cells(iRow, 3)
     
            ws.Range("A" & iRow & ":F" & iRow).Value = bl
            ws.Range("I" & iRow & ":K" & iRow).Value = bl
       Else
            prevValue = r.Cells(iRow, 3)
       End If
.
.

#vba
 
Top