gpt4 book ai didi

vba - Microsoft Visual Basic 运行时错误 91

转载 作者:行者123 更新时间:2023-12-04 22:01:34 25 4
gpt4 key购买 nike

当它到达 Cells.Find 时,它会给出运行时错误“91”
“对象变量或未设置 block 变量”。

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在你的模块中声明所有变量类型
  • 始终使用变量限定对象
  • 直接处理对象(避免 .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

    关于vba - Microsoft Visual Basic 运行时错误 91,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34071846/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com