简体   繁体   中英

Format merged and unmerged cells in excel vba

I have a range in my excel sheet from A1:Q50.

I have highlighted some cells with yellow fill (so that user can identify it as an input cell). Some of these cells are merged.

I am trying to set up a macro, which when triggered, should clear all cells with yellow fill (merged or unmerged) to No fill in the range A1:Q50

This code is not working

    '---START REMOVE YELLOW COLOR----

'Step 1 : Loop through all selected sheets

Dim ws              As Worksheet
For Each ws In ActiveWindow.SelectedSheets
    
    'Select all cells in the selected worksheet
    
    Range("A1:Q50").Select
    
    'Finds all cells filled with yellow color and removes it
    
    If cell.Interior.Color = vbYellow Then
        cell.Interior.Color = xlNone
    End If
    
Next ws

'---END REMOVE YELLOW COLOR----

As suggested above by Raymond Wu , it will be ideal to have a named range. It provides additional flexibility

    '---START REMOVE YELLOW COLOR----

'Step 1 : Loop through all selected sheets

Dim ws  As Worksheet
For Each ws In ActiveWindow.SelectedSheets
    
    'Select all cells in the selected worksheet
    
    Set selectedRange = Range("A1:Q50") 
' if using a range named MyRange then it'll become
' Set selectedRange = Range("MyRange")


    ' Loop over all cells in range                
    For Each cell In selectedRange.Cells
    
        'Finds all cells filled with yellow color and removes it

         If cell.Interior.Color = vbYellow Then
           cell.Interior.Color = xlNone
        End If
    Next 
Next ws

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM