How to clear cell contents based on a criteria

m_aatif

Board Regular
Joined
Apr 18, 2013
Messages
56
I have a range from A1 to F4.

I want to clear contents of the cells in range if is is other than "B"

Whats wrong eith following code?

Sub Deletecell()
Dim R As Range
Set R = Worksheets("sheet1").Range("A1:F4")
For Each Cell In R
If Cell.Value <> "B" Then
Cell.Value.ClearContents
Next
Else
End Sub
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
Try

Code:
Sub Deletecell()
Dim R As Range, Cell As Range
Set R = Worksheets("sheet1").Range("A1:F4")
For Each Cell In R
    If Cell.Value <> "B" Then Cell.ClearContents
Next Cell
End Sub
 
Upvote 0
This non-looping one-liner macro should also work for you...
Code:
Sub ClearNonBsInA1F4()
  Worksheets("Sheet1").Range("A1:F4") = Evaluate("IF(Sheet1!A1:F4<>""B"","""",Sheet1!A1:F4)")
End Sub
 
Upvote 0

Forum statistics

Threads
1,203,125
Messages
6,053,655
Members
444,676
Latest member
locapoca

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top