VBA - 冒号`:`如何在有条件的VBA代码中工作

Vit*_*ata 9 excel vba excel-vba

冒号运算符:是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
Run Code Online (Sandbox Code Playgroud)

A.S*_*S.H 12

我认为混乱来自于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
Run Code Online (Sandbox Code Playgroud)

要看到它,请改为3:

If 3 = 0 Then:
    Debug.Print 3 '<-- 3 will be printed! ;)
Run Code Online (Sandbox Code Playgroud)

总而言之,是的,:确实要在一条线上合并许多陈述

干得好@Vityata !!! :)