在窗体中的vba错误代码

嘿,首先要感谢所有人回答我的其他问题。 我对Excel VBA非常陌生,有些事情我只是被挂上了。 我有一个用户表单(没有embedded工作表),我有几个字段是货币(金额等),如果有人input一个字母,他们命中button后,他们失误,他们失去了所有的信息。 我需要错误代码,我可以告诉他们在一个msgbox,他们不应该把字符放在货币领域。 我不需要特定于这些字段,但我不希望它们在命令button将数据转储到电子表格时丢失数据。

我怎么能让他们看到错误信息,点击确定button,让我马上回到屏幕上,而不会丢失他们已经进入的数据? 基本上给他们机会纠正他们的错误,但不必重新input50场?

谢谢

没有实际的代码不能具体,但添加error handling程序到您的代码:

Sub SomeRoutine() Dim stuff On Error GoTo EH ' Code Exit Sub EH: ' Any errors with come here If Err.Number = <specific errors to trap> Then MsgBox "Oops..." 'As a debug tools, put a Resume here, ' but be sure to put a break on it, ' and don't leav it in the finished code Resume End If End Sub 

据我了解,你希望用户input数字只能在文本框中 – 对吗? 这是我通常做的。

在全局模块中添加以下function:

 Function IFF(c, t, f) Dim v If c Then v = t Else v = f IFF = v End Function 

然后在你的textbox_change事件中添加如下:

 Private Sub txtAmount_Change() txtAmount.Text = IFF(IsNumeric(txtAmounto.Text), Val(txtAmount.Text), 0) End Sub 

一旦用户input一个无效的数字,这基本上会把0放在方框中。

希望这可以帮助

与chris neilsen给出的error handling程序稍有不同

 Sub SomeRoutine On Error GoTo ErrHandler 'doesn't matter where you put it 'as long as it's before the code you want to protect 'Dim Stuff 'Do Stuff ExitRoutine: 'Note the colon(:), which makes this a label 'Any cleanup that you _always_ want Exit Sub ErrHandler: Select Case Err.Number Case <some error you want to handle specially> 'special handling Case Else 'default handling, which may include: Resume ExitRoutine End Select Resume End Sub 

请注意,最后的Resume在正常的处理过程中永远不会被击中(如果你已经正确地写了你的error handling案例),但是当你在Break模式下进行debugging的时候,可以让它设置为“Next Statement”。 这是一个简单的方法来看到哪个语句抛出错误。