条件格式 - 作为文本存储的数字

时间:2018-05-15 03:51:19

标签: vba excel-vba excel

我尝试使用VBA向列中添加条件格式,这样当单元格值不等于参考值时,请用黄色填充单元格。

183957

运行代码后,条件规则如下: enter image description here

我真正想要的是(注意scanf()周围的引号): enter image description here

这是因为我正在处理的单元格是“数字存储为文本”。如果我使用第一个条件规则,它将始终为“true”。只有第二条规则可以进行真正的比较。

enter image description here

我该如何解决这个问题?我无法控制电子表格内容。如何比较“文本与文本”与“文本与数字”?或者是否有更简单的解决方案?

1 个答案:

答案 0 :(得分:1)

你可以在VBA中完全做到这一点:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Application.EnableEvents = False

    Dim lastRow As Long, i As Long, RefVal As String 'maybe other appropriate datatype
    RefVal = Worksheets("ReferenceSheetNameHere!").Cells(1, 1).Value 'in Cells, specify coordinates of a cell with reference value!
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row

    For i = 1 To lastRow
        If Cells(i, 1).Value <> RefVal Then
            Cells(i, 1).Interior.ColorIndex = 6
        Else
            Cells(i, 1).Interior.ColorIndex = 0
        End If
    Next

    Application.EnableEvents = True
End Sub

请注意(如代码中的注释中所述),您必须指定参考值所在的位置。

此方法使用此签名处理工作表更改事件(包括单元格更改),因此它模仿自动过滤器,但功能更强大。

为了使其正常工作,此代码应粘贴在与您要处理的工作表对应的VBA文件中,即当您打开VBA编辑器时,在树的左侧应选择工作表。

相关问题