Undefined variable "file" in VBScript

时间:2016-06-16 17:53:53

标签: vbscript runtime-error fso

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.

1 个答案:

答案 0 :(得分:2)

Option Explicit表示所有变量必须在使用前声明

未声明file变量,请执行以下操作:

Dim file

将代码与其他Dim一起提交给您。