如何将立即窗口的内容写入文本文件

时间:2014-03-11 10:14:22

标签: vba immediate-window

我对VBA很新。我在< header>上搜索了很多,但我仍然没有得到它。

这是我的示例代码:

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

如何将即时窗口的输出写入文本文件或者是否有任何错误发送到errorlog.txt文件?

我尝试了一下这样的事情:

sub test()
    dim gofs:set gofs=createobject("scripting.filesystemobject")
    dim tsout:set tsout=gofs.createtextfile(output)

2 个答案:

答案 0 :(得分:2)

您可以根据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

答案 1 :(得分:0)

对于errorlog.txt,请尝试:

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