21

Possible Duplicate:
Any way to automatically move contents of immediate window into a text file?

Is it possible to log the Debug.Print output to a text file instead of the Immediate window in Excel VBA?

Community
  • 1
  • 1
DPD
  • 1,734
  • 2
  • 19
  • 26
  • 1
    No, you'll need to write the file directly. – Tim Williams Dec 13 '12 at 05:29
  • 1
    Writing (or appending) to a CSV file makes sense. http://stackoverflow.com/questions/9442215/reading-and-writing-a-csv-file-using-filesystemobject/9442846#9442846 – brettdj Dec 13 '12 at 05:51
  • 2
    Check out here, you use `FileSystemObject` [Remou's article](http://www.tek-tips.com/viewthread.cfm?qid=1308229) If you still have issues, do update the question by appending any relevant code you have tried. Then we are happy to assist you futher :) – bonCodigo Dec 13 '12 at 06:17
  • I would recommend to use some **best practices based logging framework** like **VBA-Logging** which supports logging to a file: http://www.bolterauer.de/consulting/dev/vbatools/vba_logging/VBALogging.html – Andreas Covidiot Dec 16 '18 at 12:13

1 Answers1

33

You should see the fabulous answer by Jean-François Corbett here:

As he states, it makes little sense to write to the immediate window, then copy and paste it when you could just write to an output txt file at the same time (or just the txt file if that is what you want).

Example from his answer:

Dim s As String
Dim n As Integer

n = FreeFile()
Open "C:\test.txt" For Output As #n

s = "Hello, world!"
Debug.Print s ' write to immediate
Print #n, s ' write to file

Close #n
Community
  • 1
  • 1
Gaijinhunter
  • 14,587
  • 4
  • 51
  • 57
  • Thanks for distilling this down. It worked well for me. – Igor Mar 02 '16 at 19:22
  • 4
    I would suggest a very subtle modification: `Open "C:\Test.txt" For Append As #n` This will build up a log file instead of replace it with each call. Of course you'll need to add some code somewhere else to delete the file on a regualr basis. – Adam Schumph Nov 15 '19 at 02:55
  • @AdamSchumph - deleting the file could be solved by making the file date dependent instead - many software packages out in the world have a daily log file for the output so it's not losing critical data. If you wanted files to overwrite based on the day of the month, you could use that number range of 1-31 instead of fully qualified dates – k1dfr0std Jun 07 '23 at 03:04