【问题标题】:vba issue with error handling错误处理的vba问题
【发布时间】:2017-07-28 14:20:17
【问题描述】:

关于我的床单的所有信息都解释了HERE。但我会很快解释一下:

我有 3 张纸 (Plan1, BANCO and DB)。 Plan1 已命名我插入信息的范围,此信息存储在 BANCO 并复制到 BD(最后一个保存所有过去的信息,而 BANCO 仅插入最后的信息)。

我还有一个代码来验证命名范围alocacao 是否已经存在于BD 上,如果存在,它们会再次加载到Plan1 上。在此之后,您可以使用以下代码将新名称插入到名为 substituit_aloc 的范围内后更改 alocacao 的名称:

Sub SubstituirProduto_Click()
Dim FoundCell As Range, FirstAddr As String, fnd As String, newAloc As Range, i As Long

On Error GoTo Catch

    fnd = Sheets("Plan1").Range("alocacao").Value
    Set newAloc = Sheets("Plan1").Range("substituir_aloc")

    Set FoundCell = Sheets("BD").Columns(5).Find(what:=fnd, _
        After:=Sheets("BD").Cells(Rows.Count, 5), Lookat:=xlPart, _
        LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlNext)

    If Not FoundCell Is Nothing Then
        FirstAddr = FoundCell.Address
    End If

    Do Until FoundCell Is Nothing
        i = i + 1
        FoundCell.Value = newAloc.Value

        Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell)
        If FoundCell.Address = FirstAddr Or i >= 30 Then
            Exit Do
        End If
    Loop

Catch:
MsgBox "Substituido!"

End Sub

有时有效,有时有效:

运行时错误 91:对象变量或未设置块变量

还有高亮线:

If FoundCell.Address = FirstAddr Or i >= 30 Then

尽管有错误,但它会在不影响最终结果的情况下做它需要做的事情。因此我添加了On Error GoTo Catch 只是为了不显示错误消息并完成运行代码,但我仍然收到错误消息。

有人知道为什么它仍然显示错误消息而没有被我的错误处理捕获吗?

【问题讨论】:

  • Option Explicit 添加到模块的最顶部,然后编译。
  • @braX 我已经这样做了并且得到了同样的结果。问题是有时它可以正常工作,但有时它仍然会无缘无故地出现错误(至少对我而言)。
  • @braX 没有错误处理错误发生在If FoundCell.Address = FirstAddr Or i >= 30 Then行上

标签: vba excel


【解决方案1】:
If Not FoundCell Is Nothing Then
  If FoundCell.Address = FirstAddr Or i >= 30 Then
     Exit Do
  End If
End If

【讨论】:

  • 为什么是If Not FoundCell Is Nothing Then 而不是If FoundCell Is Nothing Then
  • 因为如果是Nothing,它将没有Address 属性可供读取。
【解决方案2】:

在下面的代码中,在测试地址之前,FoundCell 可能被设置为空(如果 findnext 不返回任何内容),这会报错。

    Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell)
    If FoundCell.Address = FirstAddr Or i >= 30 Then
        Exit Do
    End If

在地址测试之前测试 FoundCell 是否为空:

Do Until FoundCell Is Nothing
    i = i + 1
    FoundCell.Value = newAloc.Value

    Set FoundCell = Sheets("BD").Columns(5).FindNext(After:=FoundCell)
    If FoundCell is nothing then Exit Do
    If FoundCell.Address = FirstAddr Or i >= 30 Then Exit Do
Loop

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2014-07-31
    • 1970-01-01
    • 2017-07-20
    • 2016-02-26
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多