OpenTextFile returns a TextStream that you can then close. The problem with your code is you keep no reference to it, and instead chains the ReadAll
method.
In theory, this should be OK. By not keeping a reference to the TextStream
object it's reference count will immediately become zero once the ReadAll
method has completed. When the reference count to an object reaches zero the script engine knows it can now safely free the object, and the process of freeing a TextStream
will automatically close the file.
Unfortunately there's a problem with this. Although you can be sure the script engine will free the object, you cannot be sure when it will free the object. Script engines usually implement performance tuning techniques, and one example would be not freeing an object immediately but deferring that until the engine is less busy or has a more opportune moment.
There are many examples of people experiencing unexpected/undesirable behaviour from the VBA garbage collector not freeing memory immediately, but here's one where it was causing excessive memory usage when running a script, but the problem didn't occur when stepping through the code because the garbage collector had plenty of idle time to free memory. Note Edward's second reply, where he suggests implementing a Sleep call just so the garbage collector has idle time to free memory.
With all this taken into consideration, if you want to be sure the file is closed by the time you come to delete it, you must take ownership of closing the file instead of relying on the script engine to do it when the reference count reaches zero, so try this...
Dim fso, myStream
Set fso = CreateObject("Scripting.FileSystemObject")
Set myStream = fso.OpenTextFile(filepath)
mytempstring= myStream.ReadAll
myStream.Close
fso.deletefile filepath, True