【问题标题】:Microsoft Visual Basic Run-Time error 91Microsoft Visual Basic 运行时错误 91
【发布时间】:2015-12-04 04:54:19
【问题描述】:

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

【问题讨论】:

    标签: vba excel


    【解决方案1】:
    1. 始终在您的模块中使用Option Explicit 并声明所有变量类型
    2. 始终使用变量限定对象
    3. 直接处理对象(避免使用.Select.Activate
    4. 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
    

    【讨论】:

    • 不错的提示,我发现通过遵守前三个提示,与不使用 Option Explicit 或避免使用 @987654328 相比,您可以了解更多关于 VBA 以及如何使用它的知识@.
    • 说得好@BruceWayne。 :)
    • 这是唯一突出一个单元格还是所有单元格的配偶?意思是当我运行宏时只是选择上午 12:00:00 的单元格之一,而不是全部
    • 是的,它只做 1。你需要它来选择凌晨 12:00:00 的所有单元格吗?并突出显示它们?
    • 是的,我需要更改什么 - 有没有办法在找到单元格后将单元格格式化为日期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多