Microsoft Visual Basic运行时错误91

时间:2015-12-03 16:58:32

标签: excel vba excel-vba

当它到达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

1 个答案:

答案 0 :(得分:3)

  1. 始终在模块中使用Option Explicit并声明所有变量类型
  2. 始终使用变量限定对象
  3. 直接使用对象(避免.Select.Activate
  4. 您的Find来电中的语法已关闭。无需在括号中包含变量w
  5. (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