简体   繁体   中英

IF Statement With OR and AND

Below is my current if statement. I'm trying to check if certain files exist and it appears that my first check, with the (or/and) is not picking up any of those files and thus failing down to the msgbox statment. I've added ( ) where I thought it makes sense but still doesn't pick up any file.

Currently, files 2.txt and 4.txt do exist in C:\\Temp.

Any suggestions on what I'm missing?

If (My.Computer.FileSystem.FileExists("C:\Temp\1.txt") Or _
    My.Computer.FileSystem.FileExists("C:\Temp\2.txt") Or _
    My.Computer.FileSystem.FileExists("C:\Temp\3.txt")) And _
    My.Computer.FileSystem.FileExists("C:\Temp\4.txt") Then

<<do something here1>>

Else

Msgbox("No files exist.")

EndIf

Ultimately I was missing a paren.

Thanks to @Dan Puzey for suggesting the use of Boolean to check if the file existed. While using this, my file truly did not exist because the file had an extra space.

I ended up still using the IF statement, adding two extra parens and now it appears to working.

@varocarbas had originally suggested this as an answer (still not quite sure why it was deleted though) but wanted to give credit where credit was due.

If ((My.Computer.FileSystem.FileExists("C:\Temp\1.txt") Or _
    My.Computer.FileSystem.FileExists("C:\Temp\2.txt") Or _
    My.Computer.FileSystem.FileExists("C:\Temp\3.txt"))) And _
    My.Computer.FileSystem.FileExists("C:\Temp\4.txt") Then

<<do something here1>>

Else

Msgbox("No files exist.")

EndIf

If you want check are all files existed then use AndAlso :
will return true if all four files exist

If  My.Computer.FileSystem.FileExists("C:\Temp\1.txt") AndAlso
    My.Computer.FileSystem.FileExists("C:\Temp\2.txt") AndAlso
    My.Computer.FileSystem.FileExists("C:\Temp\3.txt") AndAlso
    My.Computer.FileSystem.FileExists("C:\Temp\4.txt") Then

    <<do something here1>>

Else

   Msgbox("No files exist.")

EndIf

If you want to check if any from files exist then use OrElse
will return true if any from these file exist

If  My.Computer.FileSystem.FileExists("C:\Temp\1.txt") OrElse
    My.Computer.FileSystem.FileExists("C:\Temp\2.txt") OrElse
    My.Computer.FileSystem.FileExists("C:\Temp\3.txt") OrElse
    My.Computer.FileSystem.FileExists("C:\Temp\4.txt") Then

    <<do something here1>>

Else

   Msgbox("No files exist.")

EndIf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM