[英]VBA Excel Do While Loop Runtime Error
Very new to coding with VBA in excel, what I'm trying to do is have a Do While loop that takes user input and if it is either not a number or less than 0 returns an error message and re-prompts the user to enter a value until it hits the prerequisites. 在Excel中使用VBA进行编码非常新,我要做的是有一个Do While循环,该循环需要用户输入,如果它不是数字或小于0,则会返回错误消息并再次提示用户输入一个值,直到达到前提条件为止。 I have tried doing this in a few ways but cant seem to figure out the specifics behind it.
我尝试了几种方法,但似乎无法弄清其背后的细节。 My code currently looks like:
我的代码当前如下所示:
Function getQuantity(prompt)
Dim quantity As String
quantity = InputBox(prompt)
Do While quantity < 0
If Not IsNumeric(quantity) Then
MsgBox ("Incorrect Value, Numbers Only Please!")
quantity = InputBox(prompt)
End If
Loop
End Function
When written like this I get runtime errors. 当这样写的时候,我得到运行时错误。
If I just use: 如果我只使用:
Function getQuantity(prompt)
Dim quantity As String
quantity = InputBox(prompt)
If Not IsNumeric(quantity) Then
MsgBox ("Incorrect Value, Numbers Only Please!")
quantity = InputBox(prompt)
End If
End Function
this, it does what I want except it only re-prompts once before continuing because it is not in a loop. 这样,它可以执行我想要的操作,只是它不在循环中才再次提示一次。 Basically I want it to loop until it gets a number that is 0 or greater, and displays the error message and re-prompts the user until this happens.
基本上,我希望它循环播放直到它得到一个等于或大于0的数字,并显示错误消息并再次提示用户,直到发生这种情况为止。
Thanks in advance for any help! 在此先感谢您的帮助!
Have made a couple of changes to your code: 对您的代码进行了几处更改:
You might also want to consider allowing the user to use the cancel option from the input box. 您可能还需要考虑允许用户使用输入框中的“取消”选项。 This will return an empty string and as it stands would be confusing and a little annoying for the user if they clicked cancel and was continuously told to enter a number.
这将返回一个空字符串,并且如果用户单击“取消”并不断被告知输入数字,那么这将使用户感到困惑和烦恼。 You could return a default value in this case perhaps, depends on how you need to use this function.
在这种情况下,您可能会返回默认值,具体取决于您需要如何使用此函数。
Also, this function will currently allow the user to enter integers and decimals, presumably this is what you need. 另外,该功能当前允许用户输入整数和小数,大概就是您所需要的。 It's a good idea to use specific types for your functions (as well as for their parameters) so adding As String to the prompt parameter and perhaps As Double to the function would make the code clearer and give you more compile time safety.
为函数(及其参数)使用特定类型是个好主意,因此将As String添加到提示参数,或者将As Double添加到函数将使代码更清晰,并为您提供更多的编译时安全性。
Function getQuantity(prompt)
Dim quantity As String
quantity = InputBox(prompt)
Do While Not IsNumeric(quantity) Or Val(quantity) < 0
MsgBox ("Incorrect value, please enter a valid number of zero or above")
quantity = InputBox(prompt)
Loop
getQuantity = Val(quantity)
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.