我有一个宏代码来突出显示工作表中的单元格,其中值是来自另一个工作表,而单击一个单独的工作表上的按钮但它返回的值无法找到/无两张纸上的价值实际上都是一样的。
单元格的值是日期值。
第一个是预期的工作表,第二个是代码
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
答案 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