【问题标题】:Why does this IF statement not require an End IF为什么这个 IF 语句不需要 End IF
【发布时间】:2012-09-10 14:49:15
【问题描述】:

我正在使用以下代码快照循环浏览文件夹中的文件,它有一个简单的If 来检查文件夹中是否有文件,如果没有则退出。我已经意识到它不需要 End If 最后正确编译。但是,我想添加一个 msgbox 来解释它退出的原因,为此我需要在我的代码中引入一个 End If

为什么会这样?

原始代码

If Len(strfilename) = 0 Then Exit Sub
    Do Until strfilename = ""
       'Do some stuff
    strfilename = Dir()
Loop

使用 MsgBox

If Len(strfilename) = 0 Then
    MsgBox ("No Files Found")
    Exit Sub
Else
    Do Until strfilename = ""
        'Do some stuff
    strfilename = Dir()
    Loop
End If

【问题讨论】:

    标签: loops if-statement excel vba


    【解决方案1】:

    if有单行形式:

    if (expr) then X
    

    其中X 必须在同一,这对于单个表达式来说很好:

    if 1=1 then exit sub
    

    或奇怪但合法的(使用:继续字符)

    if 1 = 1 Then MsgBox ("No Files Found"): Exit Sub
    

    最好使用更易读的块形式编写,需要end if 告诉编译器if 块何时结束:

    if 1 = 1 Then 
       MsgBox ("No Files Found")
       Exit Sub
    end if
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 2019-06-18
      • 2011-12-03
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多