如果Font.Color不是黑色,则删除单元格

我有一个我无法理解的问题,这是脚本:

Sub WorksheetLoop() Dim WS_Count As Integer Dim I As Integer Dim ws As String Dim sht As Worksheet ' Set WS_Count equal to the number of worksheets in the active ' workbook. WS_Count = ActiveWorkbook.Worksheets.Count ws = ActiveSheet.Name ' Begin the loop. For I = 1 To WS_Count For Each sht In ActiveWorkbook.Worksheets ws = Worksheets(I).Name Dim x As Range Set x = Worksheets(I).UsedRange x.ClearComments x.Replace What:="*€£$*", Replacement:="" For Each Cell In Worksheets(I).UsedRange If x.Font.Color <> Black Then x.Delete End If Next Next sht Next I End Sub 

所有的代码与例外一起工作:

 For Each Cell In Worksheets(I).UsedRange If x.Font.Color <> Black Then x.Delete End If Next 

我试过改变这个黑色,这仍然是行不通的。 我已经尝试过,在这一点上,它从来没有发现有资格删除单元格的单元格。

你需要在循环中引用Cell 。 喜欢这个:

 For Each Cell In Worksheets(I).UsedRange If Cell.Font.Color <> vbBlack Then Cell.Delete End If Next 

你不能直接在VBA中引用颜色。 相反,你需要使用他们的数字参考。 由于黑色是0,所以你的代码应该看起来像这样

 For Each x In Worksheets(I).UsedRange If x.Font.Color = 0 Then x.Delete End If Next 

我也将For Each Cell更改为x,因为这是您在代码中定义的variables。 在这种情况下,你想testing单元格是否等于黑色,而不是不等于

在你的循环For Each Cell In Worksheets(I).UsedRange ,你正在循环与CellRange对象)的Range ,然后你检查是否If x.Font.Color <> Black Then而不是If Cell.Font.Color <> Black Then

此外, Cell.Font.Color返回一个数值,它应该comapre对vbBlack而不是Black

修改的代码

 Option Explicit Sub WorksheetLoop() Dim WS_Count As Long Dim I As Long Dim ws As String Dim sht As Worksheet Dim x As Range ' define outside the loop Dim C As Range ' Set WS_Count equal to the number of worksheets in the active workbook WS_Count = ActiveWorkbook.Worksheets.Count ' Begin the loop. For I = 1 To WS_Count With Worksheets(I) 'For Each sht In ActiveWorkbook.Worksheets ' <-- No need for this loop ws = .Name Set x = .UsedRange x.ClearComments x.Replace What:="*€£$*", Replacement:="" For Each C In x ' I replaced Cell with C (Cell is too close to Cells) If C.Font.Color <> vbBlack Then C.Delete End If Next C ' Next sht End With Next I End Sub