如何检查哪一行 VBA 代码导致错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16398261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check which line of VBA code is causing errors
提问by seigna
I am trying to debug a long code I wrote and I need to step line by line.
我正在尝试调试我写的很长的代码,我需要一行一行地逐步调试。
The thing is I am on a mac and don't know how to use an F8 in that case. Could anyone tell me how can I do that otherwise and how do I know which line is causing problems with execution?
问题是我在 mac 上,在这种情况下不知道如何使用 F8。谁能告诉我我该怎么做,我怎么知道哪一行导致执行问题?
回答by Siddharth Rout
To check which line is giving you the error, you can use the ERL
property. See this sample code below.
要检查哪一行给您错误,您可以使用该ERL
属性。请参阅下面的示例代码。
Sub sample()
Dim i As Long
On Error GoTo Whoa
10 Debug.Print "A"
20 Debug.Print "B"
30 i = "Sid"
40 Debug.Print "A"
50 Exit Sub
Whoa:
MsgBox "Error on Line : " & Erl
End Sub
For this to work, you will have to number the code lines as I have done above. Run the above code and see what happens.
为此,您必须像我上面所做的那样对代码行进行编号。运行上面的代码,看看会发生什么。
回答by Dick Kusleika
Sub Main()
Dim lNum As Long
On Error GoTo ErrHandler
lNum = 1 / 0
ErrExit:
Exit Sub
ErrHandler:
Debug.Print Err.Description
Stop
Resume
End Sub
When you get to Stop, then Step Into twice. If you don't have F8, you should have a menu item for stepping into a line. Resume will take you back to the line that caused the error.
当您到达 Stop 时,然后 Step Into 两次。如果您没有 F8,您应该有一个用于单步执行的菜单项。Resume 将带您回到导致错误的那一行。
回答by saru_
- Right click the toolbar.
- Choose "Customize..."
- Select "Debug"
- Drag "Step Into" into your toolbar.
- 右键单击工具栏。
- 选择“自定义...”
- 选择“调试”
- 将“步入”拖到您的工具栏中。