Search code examples
vbscriptms-officespecial-folders

Create a text file in %temp% and write content in it using vbs


Basically, I want to create a new file and write in it in a directory on the PC, pointed to by the %TEMP% variable. However, the revised code below does not work:

Dim oFile
Dim shell
Set oShell = CreateObject("WScript.Shell")
user = oShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = CreateObject("Wscript.Shell")
Set oFile = oFile.CreateTextFile("%Temp%\d.txt")
oFile.WriteLine "here is my contant"
oFile.Close

Error Message:

run time error
line no: 3
object required

Old Code

Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "%TEMP%\myfile.txt"
Set tf = fso.CreateTextFile(FileName, True)

If I use the file name "C:\myfile.txt" it works fine.

Error Message:

Path not found


Solution

  • In VBA, you can just use Environ("TEMP") to expand the Environment variable - if this does not work in VBScript, you may need to bind the WScript.Shell object and use the ExpandEnvironmentStrings property instead, like so:

    Set oShell = CreateObject("WScript.Shell")
    FileName = oShell.ExpandEnvironmentStrings("%TEMP%") & "\myfile.txt"
    Set oShell = Nothing
    

    Following from comments below

    Here is a "fully fixed" code:

    'Declare variables/objects first
    Dim fso AS Object, oFile AS Object
    Dim oShell AS Object, FileName AS String
    
    'This bit turns "%TEMP%" into a real file path
    Set oShell = CreateObject("WScript.Shell")
    FileName = oShell.ExpandEnvironmentStrings("%Temp%\d.txt")
    Set oShell = Nothing 'Tidy up the Objects we no longer need
    
    'This bit creates the file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile(FileName)
    oFile.WriteLine "here is my content"
    oFile.Close
    Set oFile = Nothing 'Tidy up the Objects we no longer need
    Set fso = Nothing 'Tidy up the Objects we no longer need