我正在尝试跟踪工作表并突出显示作为空白值或0值(或" NaN")值返回的单元格。我写了一个嵌套的for循环为我做这个,但是,我看到一个奇怪的项目。
如果值等于0,则有问题的单元格应变为红色。但是,当我运行宏时,最终结果是所有通过if statement
条件的单元格都以黄色结束,即使为0。也许VBA将空白单元格读为0,或者单元格不是真正空白的?我犯了错误,还是我对VBA的逻辑不正确?
'i is for the columns
For i = 2 To 4 'lastColumn
totalCounter = 0
outageCounter = 0
missingCounter = 0
'j is for the rows
For j = 6 To lastRow
'highlight if production outage
If mainSheet.Cells(j, i).Value = 0 Then
mainSheet.Cells(j, i).Interior.Color = vbRed
outageCounter = outageCounter + 1
End If
'highlight if comm outage
If mainSheet.Cells(j, i).Value = "" Or mainSheet.Cells(j, i).Value = "NaN" Then
mainSheet.Cells(j, i).Interior.Color = vbYellow
missingCounter = missingCounter + 1
End If
totalCounter = totalCounter + 1
Next j
mainSheet.Cells(lastRow + 2, i).Value = missingCounter
mainSheet.Cells(lastRow + 3, i).Value = outageCounter
mainSheet.Cells(lastRow + 4, i).Value = totalCounter
答案 0 :(得分:3)
在Excel中,空单元格的默认值为零,因此您需要在检查零之前检查其中的某些内容:
Dim c As Range
For j = 6 To lastRow
Set c = mainSheet.Cells(j, i)
'highlight if production outage
If Len(c.Value) > 0 And c.Value = 0 Then
c.Interior.Color = vbRed
outageCounter = outageCounter + 1
End If
'highlight if comm outage
If c.Value = "" Or c.Value = "NaN" Then
c.Interior.Color = vbYellow
missingCounter = missingCounter + 1
End If
totalCounter = totalCounter + 1
Next j
答案 1 :(得分:1)
您可以使用Text
属性并针对0
("生产中断")和""进行检查或" NaN" ("通讯中断")
你也可以使用一些With - End With
来减少输入和内存访问
With mainSheet
For i = 2 To 4 'lastColumn
totalCounter = 0
outageCounter = 0
missingCounter = 0
'j is for the rows
For j = 6 To lastrow
With .Cells(j, i)
Select Case .Text
Case 0
'highlight if production outage
.Interior.Color = vbRed
outageCounter = outageCounter + 1
Case "", "NaN"
'highlight if comm outage
.Interior.Color = vbYellow
missingCounter = missingCounter + 1
End Select
totalCounter = totalCounter + 1
End With
Next j
.Cells(lastrow + 2, i).value = missingCounter
.Cells(lastrow + 3, i).value = outageCounter
.Cells(lastrow + 4, i).value = totalCounter
Next i
End With