Search code examples
vbaexcelexcel-2010excel-2007

VBA on Excel to delete cells with no color and neighbour cells


So I try to figure out a way to do the following trick using VBA:

Assuming we got a huge Excel file.

C500 has some text. M500 has a value and it can either have a color fill, or just being a default white cell with a number. What I want to achieve, is to delete C500 AND M500 when M500 has no color fill.

I know it is a simple task, at least it looks like that and I know that it can probably be solved just by a few lines of code. I still can't find what I need on google or stack overflow by searching for it, probably because of my poor searching skills or because what I wanna do is very specific.

Any help will be deeply appreciated and I will really love to see any similar macro websites out there that I can use as reference. Sorry if this question is already answered.


Solution

  • I'm rewriting this answer as the requirement needs to iterate over any FormatCondition defined for each cell in the range as well as other values of cell. A neat method could be found, for example, here. Basically, it consists of :

    For X = 1 To Cell.FormatConditions.Count
        With Cell.FormatConditions(X)
          If .Type = xlCellValue Then
          ...
          If CellInterior Then
              DisplayedColor = IIf(ReturnColorIndex, Cell.Interior.ColorIndex, Cell.Interior.Color)
            Else
              DisplayedColor = IIf(ReturnColorIndex, Cell.Font.ColorIndex, Cell.Font.Color)
    

    Which explores the cell for different ways to define the filling Color.

    So you should iterate over the range

    Dim rng As Range, cell As Range
    Set rng = Range("M500:M550")
    For Each cell In rng
       rem check the filling with the method in the link
       rem if it's the colorindex you want
       rem cell.Value = ''
       rem Also, get the row number and delete content of range ("C5XX")
    Next cell