VBA-冒号“:”在带条件的VBA代码中的工作方式
冒号运算符VBA-冒号“:”在带条件的VBA代码中的工作方式,vba,excel,Vba,Excel,冒号运算符:是VBA中的语句分隔符 但是,有人知道为什么前三个示例有效,而第四个(未注释时)产生错误吗 Option Explicit Public Sub TestMe() If 1 = 1 Then: Debug.Print 1 If 2 = 2 Then Debug.Print 2 If 3 = 3 Then: Debug.Print 3 ' Gives error: ' If 4 = 4 Then ' Debug.
:
是VBA中的语句分隔符
但是,有人知道为什么前三个示例有效,而第四个(未注释时)产生错误吗
Option Explicit
Public Sub TestMe()
If 1 = 1 Then: Debug.Print 1
If 2 = 2 Then Debug.Print 2
If 3 = 3 Then:
Debug.Print 3
' Gives error:
' If 4 = 4 Then
' Debug.Print 4
'Other Examples, from the comments and the answers:
:::::::::::::::::::::::::::: '<-- This seems to be ok
If 5 = 5 Then Debug.Print "5a"::: Debug.Print "5b"
If 6 = 0 Then Debug.Print "6a"::: Debug.Print "6b"
If 7 = 0 Then:
Debug.Print 7 ' Does not have anything to do with the condition...
If 8 = 0 Then Debug.Print "8a"::: Debug.Print "8b" Else Debug.Print "8c"
End Sub
选项显式
公共子TestMe()
如果1=1,则:调试。打印1
如果2=2,则调试。打印2
如果3=3,则:
调试。打印3
'给出错误:
'如果4=4,则
'调试.打印4
“其他示例,来自评论和答案:
:如果块是多行的,则它们需要匹配的端点
第一种情况可以,因为之后的命令位于同一行
出于同样的原因,第二种情况也可以,但是:在这种情况下没有区别
第三种情况之所以有效,是因为当IF语句的计算结果为True时,“:”后面没有命令。:向编译器发出信号,表示下一个命令应被视为在同一行上。后面没有任何内容,因此处理移动到下一行,该行被视为在If-Then块之外
第四种情况没有符号来告诉编译器If-Then命令是单行的,因此它正在查找块的End If
Option Explicit
Public Sub TestMe()
If 1 = 1 Then: Debug.Print 1 '<-- All on a single line - OK
If 2 = 2 Then Debug.Print 2 '<-- All on a single line - OK
If 3 = 3 Then: '<-- No command following :
Debug.Print 3 '<-- Seen as outside the If Then Block
' Gives error:
' If 4 = 4 Then
' Debug.Print 4
' End IF '<-- Required to show the end of the If Then block
End Sub
选项显式
公共子TestMe()
如果1=1,则:Debug.Print 1'我认为混淆来自3
。我们认为3
和4
的行为应该相同。实际上,3
相当于:
If 3 = 3 Then: (do nothing) 'an empty statement
Debug.Print 3 ' <-- This will be executed regardless of the previous If condition
总之,是的,:
确实是在一行上合并许多语句
干得好@Vityata!!!:) 在最后一行之后没有“如果结束”。如果4=4,则在最后一个代码中添加“:”在“Then”之后,然后:@pokemon_-Man,是的,但是数字3在没有任何结束的情况下工作得很好如果,则需要添加一个结束,如果:
直接在之后,则基本上被忽略,否则会强制它成为一行如果Debug.Print 3
执行,无论上一条语句是如果3=3,则执行还是如果3=15,则执行。当python
程序员执行vba
时,您将得到最后一条(注释)语句第一行可以,因为之后的命令在同一行上。
-但是我们有一个语句消除器,它应该被视为在另一行上。@vityta-不,使用:
命令,如果,它仍然是一行,就像如果5=5,那么Debug.Print 5:Debug.Print 5:Debug.Print 5
案例3一样,因为当如果
被计算为True
时,没有要执行的语句(除了前面/后面的伪语句:
)@Vityata-我建议您使用的示例,如果5=5,则使用Debug.Print 5:::Debug.Print 5
,但这会使答案变得太明显-一个:
仅分隔语句,即使其中一个语句是伪非语句。另外,如果你一步一步地完成你的代码,事情就会变得更加明显。@Vityata-当然,如果5=6,那么这个例子就是Debug.Print 5:::Debug.Print 5 Else Debug.Print 6:Debug.Print 6
是的,在这种情况下,你需要一个endif
If 3 = 0 Then:
Debug.Print 3 '<-- 3 will be printed! ;)