gpt4 book ai didi

VBA MsgBox 导致错误

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

在我的 VBA 项目中,我偶尔会弹出 MsgBox 以通知用户在子例程运行后某些内容已“完成”或“更新”。
如果没有 MsgBox,它似乎运行良好,但插入一个似乎给我一个错误。
不确定是否有必要在此处显示整个代码,因为它非常大,但在子程序结束时我只想...

MsgBox ("Completed")

随后是 End Sub

但是,当我运行它然后单击 Msgbox 上的 OK 时,我收到一个运行时错误,单击 DeBug 时,它会突出显示 End Sub。

有什么理由会引发这样的错误吗?
我错过了什么吗?
非常感谢

这里的一些代码
'Add unique data to new location
For i = 1 To UnqArray1.Count
rCell(i, 1) = UnqArray1(i)
Next

'Move Split Array into a new array
Set rTable2 = rCell
rng2() = rTable2.Value

'Filter into unique items
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next

'Clear location
rCell.Clear

'Add new array to location
For i = 1 To UnqArray2.Count
rCell(i, 1) = UnqArray2(i)
Next

'Find the end of the category list
lastrow = Worksheets("CatMatch").Range("Q100000").End(xlUp).Row

'Sort alphabetically
Worksheets("CatMatch").Range("Q1:Q" & lastrow).Sort key1:=Range("Q1"), order1:=xlAscending, Header:=xlNo

'Copy it to CatMatch
Worksheets("CatMatch").Range("Q1:Q" & lastrow).Copy Destination:=Worksheets("CatMatch").Range("B15")

MsgBox "Completed"

End Sub

最佳答案

我无法重现您的错误,但您几乎可以肯定的是,如果没有 MsgBox,它运行正常是不正确的。 .问题是您的代码问题被 On Error Resume Next 隐藏了。在片段中:

'Filter into unique items
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next

两条评论:

1) 为什么不使用 RemoveDuplicates方法,如果那是你想要做的?

2)如果您尝试添加重复键,您的代码使用了一个集合会引发错误的事实。这是 On Error Resume Next 的有效用法-- 但只有在完成向集合添加 key 后将其关闭。就像是:
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next
On Error GoTo 0

养成一个好习惯是考虑 On Error Resume NextOn Error GoTo 0就像定义一个代码块一样,甚至可能像我上面所做的那样缩进 block 内的代码。一个更好的习惯是不要假设只会发生一种错误。上面的代码预期错误 457可能会出现(这是与尝试添加重复键相对应的错误号 - 您需要搜索文档以找到它,或者只是在没有错误处理的情况下运行您的代码并查看它是如何崩溃的)。任何其他都表明存在其他问题。为了最大程度地安全,您可以执行以下操作:
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
If Err.Number > 0 And Err.Number <> 457 Then
MsgBox "Unhandled error: " & Err.Number
Exit Sub
End If
Next
On Error GoTo 0

这样做不会解决您的问题,但应该使您的实际问题更加明显。

关于VBA MsgBox 导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34748583/

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