当它到达Cells.Find时,它会给出运行时错误'91' “对象变量或未设置块变量”。
Sub find_highlight()
w = "12:00:00 AM"
Cells.Find(What:=(w), After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate
Range("B:B").Select
With Selection.Interior
.ColorIndex = 6
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End Sub
答案 0 :(得分:3)
Option Explicit
并声明所有变量类型.Select
或.Activate
)Find
来电中的语法已关闭。无需在括号中包含变量w
。(1到3是最佳做法,但不是必需的。将事情排除会产生意外结果。)
Option Explicit
Sub find_highlight()
Dim ws As Worksheet
Set ws = Sheets("Sheet4") 'change as needed
Dim w As String 'maybe Date?
w = "12:00:00 AM"
Dim rng As Range, sFA As String, rngFull As Range
Set rng = ws.Cells.Find(What:=w, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
sFA = rng.Address
Do 'load all cells where w exists into range
If Not rng Is Nothing And rngFull Is Nothing Then
Set rngFull = rng
ElseIf Not rng Is Nothing Then
Set rngFull = Union(rng, rngFull)
End If
Set rng = ws.Cells.FindNext(rng)
Loop Until rng Is Nothing Or rng.Address = sFA
'highlight all cells found
With rngFull.Interior
.ColorIndex = 6
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
rngFull.NumberFormat = "mm/dd/yyyy" 'format as date -> change as needed
End Sub