为什么此表上的日期不会突出显示,尽管价值相同

时间:2017-07-20 04:09:33

标签: excel vba excel-vba

我有一个宏代码来突出显示工作表中的单元格,其中值是来自另一个工作表,而单击一个单独的工作表上的按钮但它返回的值无法找到/无两张纸上的价值实际上都是一样的。

单元格的值是日期值。

第一个是预期的工作表,第二个是代码

intended sheet to highlight cells

Sub HighlightSpecificValue()
    Dim fnd As String, FirstFound As String
    Dim FoundCell As Range, rng As Range
    Dim myRange As Range, LastCell As Range
    fnd = Range("H9").Value
    Sheets("PO copy").Select
    Set myRange = ActiveSheet.UsedRange
    Set LastCell = myRange.Cells(myRange.Cells.Count)
    Set FoundCell = myRange.Find(what:=fnd, after:=LastCell)
    If Not FoundCell Is Nothing Then
        FirstFound = FoundCell.Address
    Else
        GoTo NothingFound
    End If  
    Set rng = FoundCell
    Do Until FoundCell Is Nothing
        Set FoundCell = myRange.FindNext(after:=FoundCell)
        Set rng = Union(rng, FoundCell)
        If FoundCell.Address = FirstFound Then Exit Do
    Loop
    rng.Interior.Color = RGB(255, 255, 0)
    Exit Sub
NothingFound:
    MsgBox "No cells containing: " & fnd & " were found in this worksheet"
End Sub

1 个答案:

答案 0 :(得分:0)

需要修复一些事情:

  • 您不应该尝试将String与包含日期的单元格进行比较 - 因此最好将fnd定义为Variant
  • 您当前没有指定在执行Find时是查看值还是公式,或者是否要查看部分或全部值 - 您应该明确定义这些值以避免因Excel而导致混淆使用用户上次使用的任何内容

我认为以下稍加修改的代码应该可以运行:

Sub HighlightSpecificValue()
    Dim fnd As Variant, FirstFound As String
    Dim FoundCell As Range, rng As Range
    Dim myRange As Range, LastCell As Range
    fnd = Range("H9").Value
    Sheets("PO copy").Select
    Set myRange = ActiveSheet.UsedRange
    Set LastCell = myRange.Cells(myRange.Cells.Count)
    Set FoundCell = myRange.Find(what:=fnd, _
                                 after:=LastCell, _
                                 LookIn:=xlValues, _
                                 LookAt:=xlWhole)
    If Not FoundCell Is Nothing Then
        FirstFound = FoundCell.Address
    Else
        GoTo NothingFound
    End If  
    Set rng = FoundCell
    Do Until FoundCell Is Nothing
        Set FoundCell = myRange.FindNext(after:=FoundCell)
        Set rng = Union(rng, FoundCell)
        If FoundCell.Address = FirstFound Then Exit Do
    Loop
    rng.Interior.Color = RGB(255, 255, 0)
    Exit Sub
NothingFound:
    MsgBox "No cells containing: " & fnd & " were found in this worksheet"
End Sub