在整个excel电子表格中将彩色单元格变成非填充单元格

这是我的代码似乎并没有工作。 我基本上在第三行“UsedRange.Cells中的每个单元格”得到一个“对象需要”的错误

Sub AgreeAll() Dim myRange As Range For Each cell In UsedRange.Cells If cell.Interior.Color = RGB(255, 192, 0) Then If myRange Is Nothing Then Set myRange = cell Else Set myRange = Union(myRange, cell) End If End If Next If Not myRange Is Nothing Then myRange.Interior.Color = RGB(255, 255, 255) Range("P7").ClearContents Columns("E:F").EntireColumn.Delete End If End Sub 

尝试这个 :

 Sub AgreeAll() Dim wS As Worksheet, _ myRange As Range, _ aCell As Range Set wS = ActiveSheet 'set ws =sheets("Your_Sheet's_Name") With wS For Each aCell In .UsedRange.Cells If aCell.Interior.Color = RGB(255, 192, 0) Then If myRange Is Nothing Then Set myRange = aCell Else Set myRange = Union(myRange, aCell) End If End If Next If Not myRange Is Nothing Then myRange.Interior.Pattern = xlNone .Range("P7").ClearContents .Columns("E:F").EntireColumn.Delete End If End With End Sub 

一个基本的If块的解剖:

 If [condition] = [true | false] Then '// Do something [Else] ['// Do something Else] End If 

所以在你的情况下,你会想要的东西,如:

(修改后的评论反馈)

 Dim myRange As Range For Each cell In UsedRange.Cells If cell.Interior.ColorIndex = 44 Then If myRange Is Nothing Then Set myRange = cell Else Set myRange = Union(myRange, cell) End If End If Next If Not myRange Is Nothing Then myRange.Interior.ColorIndex = xlNone Range("P7").ClearContents Columns("E:F").EntireColumn.Delete End If 

从未确定手动设置背景填充是否填充了单元格,还是通过条件格式规则填充了单元格。 如果是后者,则可以将Interior.Pattern属性设置为white或xlNone ; CF规则将覆盖您设置的任何内容。 您可以清除内容(我假设驱动CF规则)或从该单元格中删除CF规则。

AutoFilter方法可以筛选Range.DisplayFormat属性 。 .DisplayFormat包括常规格式和条件格式; 即如果你看到橙色,那么.DisplayFormat也是如此。

 Sub AgreeAll() Dim rng As Range Dim c As Long 'Application.ScreenUpdating = False With Worksheets("Sheet2") '<~~set this worksheet reference properly! 'why wait until the end to do this? It only means you have to process rtwo columns you plan to delete .Columns("E:F").EntireColumn.Delete If .AutoFilterMode Then .AutoFilterMode = False With .Cells(1, 1).CurrentRegion For c = 1 To .Columns.Count With .Columns(c) .AutoFilter Field:=1, Criteria1:=RGB(255, 192, 0), _ Operator:=xlFilterCellColor If .Cells.SpecialCells(xlCellTypeVisible).Count > 1 Then .Offset(1, 0).Interior.Pattern = xlNone For Each rng In .SpecialCells(xlCellTypeVisible) If rng.DisplayFormat.Interior.Color = RGB(255, 192, 0) Then _ rng.FormatConditions.Delete Next rng 'your code cleared P7; did you want to clear all of the orange cells? '.Offset(1, 0).ClearContents End If .AutoFilter End With Next c End With If .AutoFilterMode Then .AutoFilterMode = False End With Application.ScreenUpdating = True End Sub 

您的代码和叙述都不能充分解释Range("P7").ClearContents应该做什么。 如果你想清除橙色的细胞,那么我已经在适当的地方留下了一些评论的代码来做到这一点。

如果遇到问题,请随时发表评论,但请记住提供足够的信息,以便我可以帮助您。