如何查找范围内的特定颜色,然后如果单元格为“ =”,则将值设置为0并在单元格中保持相同的颜色

时间:2019-03-21 14:39:00

标签: excel vba

我最近开始使用VBA,我尝试可以解决这个问题,但没有成功。

基本上我想做的是找到该范围内的颜色,然后如果该单元格为空白,我想将值设置为0并保持该颜色。

下面是我创建的代码,但不适用于"If PCell.Value = "" Then"

Sub ColorCell()
    PCell = RGB(255, 204, 204)

    range("A:F").Select

    For Each cell In Selection
        If cell.Interior.Color = PCell Then
            If PCell.Value = "" Then
                Set cell.Value = 0
            End If
         End If        
    Next
End Sub

下面是电子表格的示例。

Example

非常感谢您的帮助。我整日浏览和尝试,但没有运气:(

4 个答案:

答案 0 :(得分:2)

您的代码存在一些问题:

  • Set仅应用于对象(例如WorksheetsRange)
  • 您测试PCell.Value而不是cell.Value

这是工作代码:

Sub ColorCell()
    PCell = RGB(255, 204, 204)

    Range("A:F").Select

    For Each cell In Selection
        If cell.Interior.Color = PCell Then
            If cell.Value = "" Then
                cell.Value = 0
            End If
         End If
    Next
End Sub

答案 1 :(得分:2)

您可以尝试:

Option Explicit

Sub test()

    Dim cell As Range, rng As Range
    Dim LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row '<- Get the last row of column F to avoid looping all the column

        Set rng = .Range("A1:F" & LastRow) '<- Set the range from A1 to F last row

        For Each cell In rng

            If cell.Interior.Color = RGB(255, 204, 204) And cell.Value = "" Then
                cell.Value = 0
            End If

        Next cell

    End With

End Sub

答案 2 :(得分:1)

替换:

If PCell.Value = "" Then

具有:

If Cell.Value = "" Then

替换:

Set cell.Value = 0

具有:

cell.Value = 0

也请避免选择:

Sub ColorCell()
    Dim PCell As Variant, Intersection As Range, Cell As Range
    PCell = RGB(255, 204, 204)

    Set Intersection = Intersect(Range("A:F"), ActiveSheet.UsedRange)

    If Not Intersection Is Nothing Then
        For Each Cell In Intersection
            If Cell.Interior.Color = PCell Then
                If Cell.Value = "" Then
                    Cell.Value = 0
                End If
             End If
        Next
    End If
End Sub

(代码中可能还有其他错误)

答案 3 :(得分:0)

PCell不是cell

Sub ColorCell()
    PCell = RGB(255, 204, 204)

    For Each cell In intersect(ActiveSheet.usedrange, range("A:F"))
        If cell.Interior.Color = PCell and cell.Value = "" Then
            cell.Value = 0
        End If        
    Next
End Sub