在VBA中将零值读入为缺失值

我正在尝试跟踪表单并突出显示空白值或0值(或“NaN”)值的单元格。 我写了一个嵌套for循环为我做这个,但是,我看到一个奇怪的项目。

如果值等于0,那么问题单元应该变为红色。但是,当我运行我的macros时,最终结果是所有通过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 

在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 

您可以使用Text属性,并将其与0 (“生产中断”)和“”或“NaN”(“comm outage”)进行核对

您也可以使用With - End With来减less打字和记忆访问

 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