Pr0no
Pr0no

Reputation: 4099

How can I create an If statement with multiple conditions (not: multiple statements nested) in VBS?

In PHP, if I can compare a value against a list of other values on the fly:

$extension = "pdf";
if (!in_array($extension, array("docx", "xlsx", "txt")) {
  // do stuff to the pdf
}

How could I port this to VBS? Since I couldn't figure out how to create an array on the fly as in php, I tried and if statement with 3 conditions:

extension = objFso.GetExtensionName(objFile.Path)
If Not (extension = "docx") OR (extension = "xlsx") OR (extension = "txt") Then
  // do stuff to the pdf
End If

But this does not work. The conditions are just ignored. Two questions:

  1. Why are the conditions being ignored?
  2. How can I, instead of using multiple If confitions or If statements, create an array on the fly to compare against?

Any healp is greatly appreciated.

Upvotes: 1

Views: 944

Answers (2)

user2140173
user2140173

Reputation:

The shortest way I know is (boolean type)

UBound(Filter(Array("docx", "xlsx", "txt"), "pdf")) > -1 returns False

and

UBound(Filter(Array("docx", "xlsx", "txt"), "txt")) > -1 returns True

as you can see the Array("doc", "xlsx", "txt") is created on-fly and I have replaced the extension you've used in your original question with two different strings ("pdf" and "txt")


So, for example

extension = objFso.GetExtensionName(objFile.Path)
' extension is pdf
' the below produces false which in your logic means YES it's none of them
If (UBound(Filter(Array("docx", "xlsx", "txt"), extension)) > -1) Then
  ' you assume it's pdf
  ' do stuff to the pdf
End If

Upvotes: 5

Alex K.
Alex K.

Reputation: 175768

How about select case:

extension = lcase(objFso.GetExtensionName(objFile.Path))

select case extension
   case "docx", "xlsx", "txt"
     ' is one of the above
     ' do something
   case "zzz"
     ' its a .zzz
   case else
     ' its something else
end select

In your current logic contrast

If Not True Or True ...

and

If Not (True Or True) ...

Upvotes: 3

Related Questions