0

我对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)
4

2 回答 2

2

您可以根据本文添加一些错误处理。

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
于 2014-03-11T12:32:44.543 回答
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
于 2015-09-18T00:43:09.950 回答