如果不工作

下面的代码片段是为了将单元格的样式更改为“错误”,如果单元格中存在公式错误“#REF!” 而单元格3列留给它的内容中没有“Gesamtergebnis”文本。 但是,为什么下面的代码还有“Gesamtergebnis”写了三个单元格的单元格,好像“AND”子句的第二部分被忽略了?

For Each cell In Final.Worksheets("PIVOT").UsedRange.Cells.SpecialCells(xlFormulas) If cell.Value = "Error 2023" And cell.Offset(0, -3).Value = "Gesamtergebnis" Then cell.Style = "Bad" Next cell 

谢谢,Bartek

尝试以下方法

 Sub ErrTest() Dim cell As Range Dim errval As String Set cell = Range("A1") If IsError(cell) Then errval = cell.Value Select Case errval Case CVErr(xlErrDiv0) MsgBox "#DIV/0! error" Case CVErr(xlErrNA) MsgBox "#N/A error" Case CVErr(xlErrName) MsgBox "#NAME? error" Case CVErr(xlErrNull) MsgBox "#NULL! error" Case CVErr(xlErrNum) MsgBox "#NUM! error" Case CVErr(xlErrRef) MsgBox "#REF! error" Case CVErr(xlErrValue) MsgBox "#VALUE! error" Case Else MsgBox "This should never happen!!" End Select End If End Sub 

这里是文档https://msdn.microsoft.com/en-us/vba/excel-vba/articles/cell-error-values

对于你的情况,你可以使用以下function

 Function refError(cell As Range) As Boolean Dim errval As Variant If IsError(cell) Then errval = cell.Value If errval = CVErr(xlErrRef) Then refError = True End If End Function 

而你的代码会是这样的

 For Each cell In Final.Worksheets("PIVOT").UsedRange.Cells.SpecialCells(xlFormulas) If refError(cell) And cell.Offset(0, -3).Value = "Gesamtergebnis" Then cell.Style = "Bad" Next cell 

处理你的情况的更好的方法是使用参数16 SpecialCells 。 带有这些参数的SpecialCells让您select范围内的公式中的错误。

这是你正在尝试?

 Sub Sample() Dim ErrRange As Range Dim rng As Range Dim aCell As Range Set rng = Final.Worksheets("PIVOT").UsedRange.Cells On Error Resume Next Set ErrRange = rng.SpecialCells(xlCellTypeFormulas, 16) On Error GoTo 0 If Not ErrRange Is Nothing Then For Each aCell In ErrRange If aCell.Offset(, -3).Value = "Gesamtergebnis" Then aCell.Style = "Bad" Next aCell End If End Sub 

截图

我正在使用aCell.Interior.ColorIndex = 3而不是aCell.Style = "Bad"作为演示目的。 它将单元格变为红色。

在这里输入图像说明