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 

  1. 在模块中始终使用Option Explicit并声明所有variablestypes
  2. 始终使用variables限定对象
  3. 直接使用对象(避免.Select.Activate
  4. 您的语法在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