phriol
phriol

Reputation: 101

Undefined variable "file" in VBScript

I have this VBScript code that's supposed to write to every file in a directory:

Option Explicit

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")

Dim dir: dir = fso.GetAbsolutePathName(".") & "/important/"

For Each file In fso.GetFolder(dir).Files
    If UCase(fso.GetExtensionName(file.Name)) = "JS" Or UCase(fso.GetExtensionName(file.Name)) = "VBS" Then
        Dim op: Set op = file.OpenAsTextStream(2,-2)
        op.Write "This file has been written!"
        op.Close
    End If
Next

MsgBox("Done!")

But the Windows Script Host keeps complaining and telling me that I have an undefined variable named "file". The error occurs on line 7. I have no idea why this error is occuring and help would really be appreciated.

Upvotes: 2

Views: 1365

Answers (1)

Alex K.
Alex K.

Reputation: 175766

Option Explicit means All variables must be declared before use.

The file variable is not declared, do so by adding:

Dim file

To your code along with the other Dims.

Upvotes: 3

Related Questions