Microsoft Visual Basic运行时错误91
当它到达Cells.Find时,它会给出一个运行时错误“91”“对象variables或块variables未设置”。
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
- 在模块中始终使用
Option Explicit
并声明所有variablestypes - 始终使用variables限定对象
- 直接使用对象(避免
.Select
或.Activate
) - 您的语法在
Find
呼叫中closures。 没有必要将variablesw
包装在括号中。
(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