在 excel vba 中格式化合并和未合并的单元格

Format merged and unmerged cells in excel vba

我的 excel sheet 中有一个范围 A1:Q50。

我用黄色填充突出显示了一些单元格(以便用户可以将其识别为输入单元格)。其中一些单元格已合并。

我正在尝试设置一个宏,当它被触发时,应该清除所有带有黄色填充(合并或未合并)的单元格到无填充范围 A1:Q50

此代码无效

    '---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----

正如上面 Raymond Wu 所建议的,最好有一个命名范围。它提供了额外的灵活性

    '---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