Question

I have a vbscript function with creates and opens a text file. I want to return the file handle from the function back to the main body of the code. Unfortunately, I'm getting an object doesn't support this property or method error.

Ultimately, I'll be setting the code up where I'll have a debug script which will have functions for opening, writing, reading, and closing files. Then, I can import this script into another vbscript file and use it for debugging purposes. But, first, I need to get the code below to work.

Thank you in advance.

Here is the code:

Function OpenFileWrite(sDirectory, sFile)
    Dim objFSO 'As FileSystemObject
    Dim objTextFile 'As Object

    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' Check that the strDirectory folder exists
    If objFSO.FolderExists(sDirectory) Then
            Set objFolder = objFSO.GetFolder(sDirectory)
    Else
            Set objFolder = objFSO.CreateFolder(sDirectory)
            WScript.Echo "Just created " & sDirectory
    End If

    If objFSO.FileExists(sDirectory & "\" & sFile) Then
            Set objFile = objFSO.GetFile(sDirectory & "\" & sFile)
    Else
            Set objFile = objFSO.CreateTextFile(sDirectory & "\" & sFile)
            Wscript.Echo "Just created " & sDirectory & "\" & sFile
    End If

    Set objTextFile = objFSO.OpenTextFile(sDirectory & "\" & sFile, ForWriting, True)

    OpenFileWrite = objTextFile

End Function

sDirectory = "\"
sFile = "debug.txt"

Set ObjFile = OpenFileWrite(sDirectory, sFile)
Was it helpful?

Solution

You need Set to assign an object to a variable or the function's return value:

OpenFileWrite = objTextFile
==>
Set OpenFileWrite = objTextFile

(In Set OpenFileWrite = objTextFile the Set obeys the rule "Use Set to assign an Object"; the OpenFileWrite = 'implements' the rule "assign to the function name to specify the return value".)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top