Home » excel » excel – How to clear all contents within a given range based on if one column returning zero value?

# excel – How to clear all contents within a given range based on if one column returning zero value?

Posted by: admin May 14, 2020 Leave a comment

Questions: So say I’m trying to clear contents within Range P4:R12. Column P has alphabetical value, but Q and R have numerical. I want to clear contents off all 3 columns P4, Q4, and R4 based on the fact that column Q is 0, and shift contents up on P through Q only once the content is cleared on P through Q based on Q = 0.

Can someone help me? I’m using below code, but it only clears contents on columns Q and R zero values. I want to clear column P alphabetical content as well if values are 0 in column Q. No formulas involved in cells. All values.

You can see on picture above any cell that doesn’t have bales amount i want to clear portfolio content as well, and then shift cells up, without messing with formatting. Portfolio is column P, Bales is Q, and COGS is column R.

``````Sub Equity()
Dim q As Range
For Each q In Range("P4:R12")
If q.Value = xlnullstring Then
q.Resize(1, 4).Value = xlnullstring
End If
Next
Application.ScreenUpdating = True
End Sub
``````
How to&Answers:

EDIT: this will do the consolidation of the remaining rows

``````Sub Equity()

Dim rng As Range, rw As Range, arr, i As Long, n As Long

Set rng = Range("P4:R12")
ReDim arr(1 To rng.Rows.Count, 1 To rng.Columns.Count)

For Each rw In rng.Rows
If Application.CountA(rw) > 0 And rw.Cells(2) <> "" Then
i = i + 1
For n = 1 To UBound(arr, 2)
arr(i, n) = rw.Cells(n)
Next n
End If
Next rw

rng.Value = arr
End Sub
``````

### Answer：

Thanks for trying guys, but I used a combination of different codes to achieve the result I was looking for. See below. This worked!

``````Sub Equity()
Dim LastRow As Long
Dim I As Long
Application.ScreenUpdating = False
LastRow = Range("Q" & rows.Count).End(xlUp).Row
For I = LastRow To 2 Step -1
If (Cells(I, "Q") = 0) Then
With Range(Cells(I, "P"), Cells(I, "R"))
.ClearContents
End With
End If
If (Cells(I, "T") = 1) Then Range(Cells(I, "A"), Cells(I,"Y")).Interior.ColorIndex = 35`
Next I
Application.ScreenUpdating = True
Range("P4:R12").Sort key1:=Range("P4"), _
order1:=xlAscending, Header:=xlNo
Application.ScreenUpdating = True
End Sub
``````

You can follow the picture model above and replace my column letter with yours if you have a similar issue.The end result looks like picture below. First part of the code clears contents based on Bales column being 0. Second part, I used sorting instead of shift contents up. 