vba :只在每个循环的第一个上做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4228466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
vba : do something only on the first for each loop
提问by l--''''''---------''''''''''''
for each element in sarray
if ... then
if this is the first time the above IF statenent was executed ... then
end if
next element
i want to do something ONLY the first time that the first IF THEN
statement is executed. i am having a lot of problems with my logic. please help!
我只想在第一次IF THEN
执行第一条语句时做一些事情。我的逻辑有很多问题。请帮忙!
回答by cdeutsch
var isExecuted = false
for each element in sarray
if ... then
if Not isExecuted Then
--do stuff
isExecuted = true
end if
end if
next element
回答by Dr. belisarius
flag = true
For each ...
if flag
do whatever with first element
flag = false
endif
do what you want with all elements ... including the first
next
回答by user472875
There is probably a better way of doing this but you can have a boolean variable first_time which will start out as true and get set to false in the if statement. You can then check
可能有更好的方法来做到这一点,但你可以有一个布尔变量 first_time ,它开始为真,并在 if 语句中设置为假。然后你可以检查
If first_time = True Then
Stuff
End If
回答by Wodzu
If I understand you correctly you have N elements, and you want to perform some operation only for the first element. So doing this like you want to do is waste of processor time.
如果我理解正确,您有 N 个元素,并且您只想对第一个元素执行某些操作。所以像你想做的那样做是浪费处理器时间。
So I would suggest to rewrite your logic without introducing a new boolean variable. It's cleaner and faster. Something like this for example:
所以我建议在不引入新的布尔变量的情况下重写你的逻辑。它更干净、更快。例如这样的事情:
Dim intCount As Integer
If (some condition) Then
DoSomething with sarray(0)
For intCount = 1 To sarray.Length
//Do something
Next intCount