[英]Highlight blank cells containing formulas using VBA
范圍"C2:E" & lastrow
, "G2:G" & lastrow
以及"Q2:R" & lastrow
包含一個動態分布到所有單元格的公式: "=IFNA(VLOOKUP($B2,CONTACTS,2/3/4/8/10/11,FALSE),"")"
其中C列返回CONTACTS表中第二列的值,D列返回第三列的值,E列返回第四列的值, 等等等等。
現在,我需要使用VBA突出顯示RED中該范圍內的所有單元格(如果其中不包含任何內容/空白),這意味着vlookup在CONTACTS表中找不到任何內容。 數據是動態的,因此沒有確定的行數,並且我不想格式化未包含在數據中的單元格。
我該怎么做? TIA!
不理想,但以下方法應該起作用。 根據需要更改工作表名稱。 理論上,如果所有單元格都有一個公式,則可以刪除IsEmpty部分。
Dim rng As Range
For Each rng In ThisWorkbook.Worksheets("Sheet1").Range("C2:E" & lastRow)
If IsEmpty(rng) Or rng = vbNullString Then rng.Interior.Color = vbRed
Next
您還可以將SpecialCells與公式一起使用,以僅對具有公式的單元格進行處理(測試是否首先出現公式,或者在未找到公式的情況下進行錯誤處理):
Dim rng As Range
For Each rng In ThisWorkbook.Worksheets("Sheet1").Range("C2:E" & lastRow).SpecialCells(xlCellTypeFormulas)
If rng = vbNullString Then rng.Interior.Color = vbRed
Next
您可以使用union
組合不同的范圍:
Dim rng As Range
With ThisWorkbook.Worksheets("Sheet1")
For Each rng In Union(.Range("C2:E" & lastRow), .Range("G2:G" & lastRow), .Range("Q2:R" & lastRow)).SpecialCells(xlCellTypeFormulas)
If rng = vbNullString Then rng.Interior.Color = vbRed
Next
End With
條件格式可以使此任務更容易。 這是在VBA中應用CFR的方法。
with thisworkbook.worksheets("sheet4").range("C:E, G:G, Q:R")
.FormatConditions.Delete
with .FormatConditions.Add(Type:=xlExpression, Formula1:="=and(iserror(--C1), C1=text(,))")
.Interior.Color = vbred
end with
end with
with thisworkbook.worksheets("sheet4").range("C:E, G:G, Q:R")
.FormatConditions.Delete
with .FormatConditions.Add(Type:=xlExpression, Formula1:="=and(istext(C1), C1=text(,))")
.Interior.Color = vbred
end with
end with
with thisworkbook.worksheets("sheet4").range("C:E, G:G, Q:R")
.FormatConditions.Delete
with .FormatConditions.Add(Type:=xlExpression, Formula1:="=and(isformula(C1), C1=text(,))")
.Interior.Color = vbred
end with
end with
您可以避免條件格式和循環
With Intersect(Range("C:E, G:G, Q:R"), Rows("1:" & lastrow))
.Interior.Color = vbRed ' first color all cells
.SpecialCells(xlCellTypeFormulas, xlNumbers).Interior.Pattern = xlNone ' then un-color those with a numeric output
End With
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.