3

I am using the following snapshot of code to loop through files in a folder, it has a simple If to check if there are files in the folder then exits if there aren't. I've realised it does not require an End If at the end to compile correctly. However, I want to add a msgbox explaining why it has exited and to do so I need to introduce an End If to my code.

Why is that?

Original Code

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

With MsgBox

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

1 回答 1

8

There is a single line form of if:

if (expr) then X

where X must be on the same line, which is nice for single expressions:

if 1=1 then exit sub

or the odd but legal (using : continuation character)

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

which is better written using the more readable block form that requires an end if to tell the compiler when the if block ends:

if 1 = 1 Then 
   MsgBox ("No Files Found")
   Exit Sub
end if
于 2012-09-18T10:44:46.990 回答