PDA

View Full Version : [SOLVED:] VBA text file write not working on close and open



vijay_s
08-17-2013, 10:47 AM
Hi folks
i'm newbie to VBA.. I'm experiencing some problem with text file write from VBA .. my code works fine until i close the file. when i reopen it, write to text file is not working, but other piece of codes are working

Below is my code


Dim FSO As FileSystemObject
Dim oFile As TextStream

'File Open
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFile = FSO.CreateTextFile("IPC_Testplan.capl", True)

oFile.WriteLine "void f_testcase_" + Worksheets("TestPlan").Cells(2, 4)
oFile.WriteLine "{"

oFile.WriteLine "}"

oFile.Close

MsgBox "generation complete"


File 'IPC_Testplan.capl' is created when i run this for first time. After i close the excel, reopen and run this(deleted already created file), no file is generated. but message box is popped up every time i run this.:help

p45cal
08-17-2013, 11:09 AM
Are you sure no file is generated? Do system-wide search for the file because you don't specify in your code where the file is to be, so the Current Directory is used and this may have been change elsewhere in your code. in the Immediate pane type:
?CurDir
and press Enter to see where the Current directory is, then look there.

vijay_s
08-17-2013, 11:23 AM
thanks for the reply p45cal

i'm not changing the path of file elsewhere. i'm using only this piece of code.

Note : When i use save as and save the file in another name, again the text file write works until i close that.

p45cal
08-17-2013, 12:07 PM
again the text file write works until i close that.If you have the text file open, say in notepad or something, I don't think you'd expect to see changes reflected in that open file (I think you're looking at a copy). I'm more than fairly sure that the file is correctly being overwritten (the True in your CreateTextFile line) by the code.

Kenneth Hobs
08-17-2013, 01:34 PM
I could not duplicate your problem.

I changed your "+" to "&". That is the string concatenation operator.

I prefer to set a path for the file so that I know where it is going.


Sub Write_IPC_Testplan()
Dim FSO As FileSystemObject
Dim oFile As TextStream

'File Open
'Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO = New FileSystemObject

Set oFile = FSO.CreateTextFile(ThisWorkbook.Path & "\IPC_Testplan.capl", True)
With oFile
.WriteLine "void f_testcase_" & Worksheets("TestPlan").Cells(2, 4).Value2
.WriteLine "{"
.WriteLine "}"
.Close
End With

Set oFile = Nothing
Set FSO = Nothing

MsgBox "generation complete"
End Sub

vijay_s
08-19-2013, 07:13 AM
It works after adding reference path during creation.





Set oFile = FSO.CreateTextFile(ThisWorkbook.Path & "\IPC_Testplan.capl", True)

:thumb

Kenneth Hobs
08-19-2013, 09:27 AM
I suspect that it worked before but as p45cal said, you did not know where it was. It probably went to your default path in Options > Save > Default file location.