Jonathan,
No, no such single statement equivalent. The reason your code is having a problem as it is, is that when nothing was found, and you exit the "for each" loop normally, the loop control variable then has no defined value (and you are using it in a following statement). It's as if you had never initialized it. When you use "exit for" you do leave the variable with a value, but I consider this poor programming (because sometimes after your "for each" loop the variable can be counted on to have a value, and sometimes not). So, if you don't care for "short circuiting" the function, then try the alternative where you just use a second variable to hold the return of the function. Hth, Chip From: Jonathan C. Cohn [mailto:[email protected]] Sent: Sunday, February 16, 2014 9:38 AM To: [email protected] Subject: Re: When a search fails how to handle. Thanks Chip, Yes I generally don't like to short circuit functions especially in a loop I find that difficult to maintain. My code is currently working except in the case where every item is checked and nothing was found. Is there a VB equivalent to the Perl line: return 0 unless ( defined( <http://perldoc.perl.org/functions/defined.html> MyVariable I might still add code to the test condition, but right now I am using two variables and two embedded loops and I'll have to verify logic again. ) ) ) Best wishes, Jonathan On Feb 15, 2014, at 5:09 PM, Chip Orange <[email protected]> wrote: Hi Jonathin, First, you should not use the variable you are using to loop through your collection, outside of the "for each" loop. It's not defined to have any value. This is why you are sometimes getting an error in the line which tries to use oChild. I'd suggest before the "for each" loop, that you set the function's return value to be "nothing"; so if you don't find it, this is what the function will return. Then, inside of the "if" inside the "for each", when you find the control, set the function's return value to be what you found, and then have a "exit function" command to stop searching. There are other ways of doing this: set a variable to "nothing" before the "for each" loop, and then set this variable to the found control if/when you find it, and then have a "exit for" as you do. After the loop, then set the function to return this variable. It comes out to be about the same as my first suggestion, but maybe you find it a little clearer. Hth, Chip -----Original Message----- From: Jonathan C. Cohn [mailto:[email protected]] Sent: Saturday, February 15, 2014 2:47 PM To: [email protected] Subject: When a search fails how to handle. Good day, I have made progress in creating a script that searches for a given control. FOR EACH oChild IN Obj.Children IF oChild.Name = MySearchItem THEN EXIT FOR END FOR ' Nex line errors when search failed. IF oChild IS NOTHING THEN ReturnValue = NOTHING ELSE ReturnValue = oChild END IF What should I be using in the second IF clause? Thanks, Jonathan
