PDA

View Full Version : 2nd time a freefile is opened, exception is thrown



weather
04-07-2015, 12:24 PM
I have created this VBA module associated with a worksheet named "Notes" The first time it runs, a file is written to this directory: "C:\Users\weather\Documents\Outlook Files\" & strTitle & ".txt" The filename is NoteBody.txt

The second time through the loop an exception is thrown at this line: Open strTitle For Output As #intFileNo with the following error:

Microsoft Visual Basic


Run-time error '52':


Bad file name or number


When the exception is thrown the value of intFileNo has incremented to 2.

I think the fix is going to be pretty simple. It has been years since I did any VBA coding. Your help would be appreciated.

weather
04-07-2015, 02:27 PM
The filename I was writing was so long that I couldn't see its entire length. Upon a closer look I saw CrLf or unallowed characters that were causing the problem. I was assuming (always dangerous) that the problem was with the filenumber. My code now removes those characters and the .txt files are being created.

mancubus
04-08-2015, 02:24 AM
i prefer using CreateTextFile method of FileSystemObject.

https://msdn.microsoft.com/en-us/library/aa265018(v=vs.60).aspx

http://www.exceltrick.com/formulas_macros/filesystemobject-in-vba/