我最近开始使用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
下面是电子表格的示例。
非常感谢您的帮助。我整日浏览和尝试,但没有运气:(
答案 0 :(得分:2)
您的代码存在一些问题:
Set
仅应用于对象(例如Worksheets
或Range)
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