VBA中的错误处理有哪些好的模式?
特别是在这种情况下我应该怎么做:
... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...
Run Code Online (Sandbox Code Playgroud)
我想处理这两个错误,并在可能发生错误的代码之后恢复执行.此外,最后的代码必须始终运行 - 无论先前抛出什么异常.我怎样才能达到这个目的?
在寻找一种方法来测试用户何时取消时InputBox,我偶然发现了这个StrPtr功能.我相信它会检查一个变量是否被分配了一个值,如果它从未被分配则返回零,如果是,则返回一些神秘数字.
这似乎是一个有用的功能!我从这段代码开始:
Dim myVar as string
myVar = InputBox("Enter something.")
MsgBox StrPtr(myVar)
Run Code Online (Sandbox Code Playgroud)
如果用户取消,消息框显示零.
太棒了!但是为什么有些人坚持认为StrPtr永远不会被使用?我读它不受支持.为什么这么重要?
一个好的答案将解释好处(超出我上面的例子)和使用该StrPtr功能的风险,可能你如何使用(或不使用)它,而不是就是否每个人都应该使用它而发表意见.
我一直在使用Daniel Klann编写的标准密码文本框(http://www.ozgrid.com/forum/showthread.php?t=72794)来隐藏密码输入.
主要问题是标准InputBox返回空字段并取消相同的方式.Application.InputBox但是能够False取消取消.
更新Daniel Klann的脚本以便与Application.InputBox我合作.怎么做?
这是丹尼尔的代码:
Option Explicit
'////////////////////////////////////////////////////////////////////
'Password masked inputbox
'Allows you to hide characters entered in a VBA Inputbox.
'
'Code written by Daniel Klann
'http://www.danielklann.com/
'March 2003
'// Kindly permitted to be amended
'// Amended by Ivan F Moala
'// http://www.xcelfiles.com
'// April 2003
'// Works for Xl2000+ due the AddressOf Operator
'////////////////////////////////////////////////////////////////////
'******************** CALL FROM FORM *********************************
' Dim pwd As String
'
' pwd …Run Code Online (Sandbox Code Playgroud)