Help with writing TEXT file
Hello,
I'm trying to write some TEXT in a text file using EXCEL VBA
My file is created correctly but I can't write any text in.
My code is:
Open strDestFile For Output As #iFileNum
' If an error occurs report it and end.
If Err <> 0 Then
MsgBox "Cannot open filename " & strDestFile
End
'write " HELLO WORLD"
Write #iFileNum, "HELLO WORLD"
Close #iFileNum
Any idea ?
Re: Help with writing TEXT file
Code:
Option Explicit
Sub Macro1()
Dim strDestFile As String
Dim iFileNum As Integer
strDestFile = "c:\JUNK.txt"
'This is one thing you are missing
iFileNum = FreeFile
Open strDestFile For Output As #iFileNum
' If an error occurs report it and end.
If Err <> 0 Then
MsgBox "Cannot open filename " & strDestFile
End
'This is one thing you are missing!
End If
'write " HELLO WORLD"
Write #iFileNum, "HELLO WORLD"
Close #iFileNum
End Sub
Re: Help with writing TEXT file
Hi,
Thanks a lot, I really like to learn from the PRO !
By the way, is it possible in VBA to automatically EXECUTE NOTEPAD and to open the created TEXT file ?
Thanks
Re: Help with writing TEXT file
Yes, Shell ("c:\myfile.txt","Notepad.exe") .. you might need the full path, been awhile since I Shelled something but yhea.
Re: Help with writing TEXT file
You might have noticed by now that your Error Popup never executes. The system error handler never lets you get that far. If you want to process your own errors you need to do the following:
Code:
' ...
' ...
'Redirect the System Error handler to your own handler
On Error GoTo ERROR_HANDLER 'Use whatever name(s) you choose for one or more error handlers
'
Open strDestFile For Output As #iFileNum
'Reset the Error handler to the normal System error handler
On Error GoTo 0
' ...
' ...
Close #iFileNum
'All the following usually goes at the end of your 'normal' executing code
Exit Sub
ERROR_HANDLER:
'Error Processing goes HERE
MsgBox "Cannot open filename " & strDestFile
End Sub
You can do a search on this forum to find more complex error handling hints.