Validating user input in inputbox

时间秒杀一切 提交于 2019-12-23 02:18:19

问题


When I run the following snippet, and enter an acceptable value, I get the desired result.

do while len(strselect) = 0  'or strselect<>"1" or strselect<>"2" or strselect<>"3"
strselect = inputbox ("Please select:" &vbcrlf&vbcrlf&_  
"1. Add an entry" &vbcrlf&vbcrlf&_  
"2. Remove an entry" &vbcrlf&vbcrlf&_  
"3. Search for an entry" &vbcrlf, "Contact Book")
if isempty(strselect) then
wscript.quit()
elseif strselect="1" then
wscript.echo "You chose 1"
elseif strselect="2" then
wscript.echo "You chose 2"
elseif strselect="3" then
wscript.echo "You chose 3"
end if
loop

However if I try constrain the validation process further (by including the remark in the do while conditions), and run the snippet again, I get the corresponding if condition triggered, but the do loop continues, instead of exiting.

I've tried using isnumeric and cstr on the do loop strselect conditions, with no joy... What am I missing to get the darn thing to exit the loop?


回答1:


You have a problem with the logic in the condition

         condition 1            condition 2       condition 3       condition 4
         v----------------v     v------------v    v------------v    v............v
do while len(strselect) = 0  or strselect<>"1" or strselect<>"2" or strselect<>"3"

Depending on value inside strselect, you have

value   c1      c2      c3      c4    
        len=0   <>"1"   <>"2"   <>"3"    c1 or c2 or c3 or c4
--------------------------------------   --------------------
empty   true    true    true    true            true
  1     false   false   true    true            true
  2     false   true    false   true            true
  3     false   true    true    false           true
other   false   true    true    true            true

In each line you have at least one condition evaluated as true, and as you are concatenating the conditions with Or operators (evaluate to true if at least one of the values is true), the full condition is evaluated as true and the code keeps looping

You only need to change the condition

Do While strselect<>"1" And strselect<>"2" And strselect<>"3"
Do While Not (strselect="1" Or strselect="2" Or strselect="3")
....


来源:https://stackoverflow.com/questions/39783736/validating-user-input-in-inputbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!