0

I am very new to VBA. I searched a lot on the <header>, but I still don't get it.

This is my sample code:

Sub test()
    a = 10
    b = 2
    c = 10 / b

    Debug.Print c
    On Error GoTo x
    x:
    If Err > 1 Then
        Debug.Print "The most recent error number is " & Err & _
          ". Its message text is: " & Error(Err)
    End If
End Sub

How do I write the output of immediate window to a text file or if any error to errorlog.txt file?

I tried a little like this:

sub test()
    dim gofs:set gofs=createobject("scripting.filesystemobject")
    dim tsout:set tsout=gofs.createtextfile(output)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I don't think you can do this. You should store your string in a variable and output the contents of this variable into your text file. – Kapol Mar 11 '14 at 10:22
  • 1
    Something like [this](http://stackoverflow.com/questions/21777595/how-to-redirect-error-to-a-text-file-in-vbs/) you are looking for? – Pankaj Jaju Mar 11 '14 at 12:16

2 Answers2

2

You can add some error handling based on this article.

Option Explicit

Sub Main()

    CreateFile ("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt")

    Dim a&, b&, c&

    a = 10
    b = 2
    c = 10 / b

    ToFile c
    On Error GoTo x
x:
    If Err > 1 Then
        ToFile "The most recent error number is " & Err & ". Its message text is: " & Error(Err)
    End If

End Sub

Private Sub CreateFile(path As String)
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oFile As Object
    Set oFile = fso.CreateTextFile(path)
    oFile.WriteLine Now & "file created by " & Environ$("username")
    oFile.Close
End Sub

Private Sub ToFile(str As Variant)

    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim ofs As Object
    If Len(Dir("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt")) > 0 Then
        Set ofs = fso.OpenTextFile("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt", 8, True)
    End If
    ofs.WriteLine str
    ofs.Close
End Sub
barsoap
  • 3,376
  • 3
  • 23
  • 21
0

for an errorlog.txt, try this:

x:
If Err > 1 Then
    Open "C:\temp\errorlog.txt" For Append As #1
    Print #1, Date & " " & Time() & " - Error " & Err & ": " & _
              Error(Err)
    Close #1
End If