【问题标题】:Run-time Error 91 - Object Variable or with Block variable not set - VBA运行时错误 91 - 对象变量或未设置块变量 - VBA
【发布时间】:2018-04-16 20:08:16
【问题描述】:

我有以下 sn-p VBA:

DatetoRun = InputBox("How far back do you want to run the MI for?", "Date backing", Format(Now(), "dd/mm/yyyy"))

'Date validation for DatetoRun
If IsDate(DatetoRun) Then       
    DatetoRun = Format(CDate(DatetoRun), "dd/mm/yyyy")
    dateStart = DatetoRun        
Else
    MsgBox "Please enter a DATE in the correct format dd/mm/yyyy"
End If

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)

iclearrow = found.Row

当执行它时,我不断得到 ​​p>

对象变量或With Block变量未设置

这让我在设置它时感到困惑:

Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)

错误发生在最后一行:

iclearrow = found.Row

不确定这是如何发生或为什么发生的。有时它也会随机工作一次,但之后会出错。没有什么是一致的!

【问题讨论】:

    标签: vba excel runtime-error


    【解决方案1】:

    如果Find在A列中找不到DatetoRun,你需要有错误处理场景。

    Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlValues, lookat:=xlWhole)
    If Not found Is Nothing Then ' find was successfull
        iclearrow = found.row
    Else ' Find failed >> raise an error
        MsgBox "Unable to find " & DatetoRun, vbCritical
    End If
    

    注意:在搜索日期时,它们实际上是以数值形式存储的,因此请尝试使用:

    Set found = Range("A:A").Find(what:=CDbl(DatetoRun), LookIn:=xlValues, lookat:=xlWhole)
    

    编辑 1: 试试下面的 Find 行:

    Set found = Range("A:A").Find(what:=DatetoRun, LookIn:=xlFormulas, lookat:=xlPart)
    

    【讨论】:

    • 嗯,这很有道理:)
    • 当使用“CDbl”时,我现在在变量“DatetoRun”上获得了类型匹配错误。这个电流被声明为一个字符串。
    • 没有它的工作,但 find 总是返回 Nothing?
    • @xTNAx 您在InputBox 中输入了什么值?什么值和格式?
    • 它是一个日期,格式为 dd/mm/yyyy。它默认为今天的日期,但用户可以编辑过去的日期。
    【解决方案2】:

    DatetoRun 类型的变量是什么?我猜是Variant

    只要Find()Date 遵循自己的逻辑,将值转换为字符串并搜索它们-Range.Find not making a difference between January and November (February and December) in VBA Excel,那么在条件之后将DatetoRun 解析为Date 是个好主意。

    像这样: DatetoRun = CDate(DatetoRun) 然后,它总是会在Range("A:A") 中“找到”,如果它存在的话。 If Not found Is Nothing Then 也是个不错的主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 2017-05-20
      相关资源
      最近更新 更多