为什么这张纸上的date没有突出显示,虽然值是一样的

我有一个macros代码来突出显示表单中的单元格,其中值来自另一个表单上的button单击一个单独的工作表上,但它返回值无法find/无法find两个表单上的值实际上是相同。

单元格的值是一个date值。

第一个是预定的表单,第二个是代码

打算用来突出显示单元格

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 

有几件事情需要修正:

  • 您不应该尝试将String与包含date的单元格进行比较 – 因此最好将fnd定义为Variant
  • 您目前没有指定在查找时是查看值还是公式,还是查看部分或整个值 – 您应该明确定义这些值,以避免由于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