我对VBA很陌生。我在
这是我的示例代码:
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)
您可以根据本文添加一些错误处理。
Option Explicit
Sub Main()
CreateFile ("C:Users" & Environ$("username") & "DesktopNewFile.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") & "DesktopNewFile.txt")) > 0 Then
Set ofs = fso.OpenTextFile("C:Users" & Environ$("username") & "DesktopNewFile.txt", 8, True)
End If
ofs.WriteLine str
ofs.Close
End Sub
对于errorlog.txt,尝试如下:
x:
If Err > 1 Then
Open "C:temperrorlog.txt" For Append As #1
Print #1, Date & " " & Time() & " - Error " & Err & ": " & _
Error(Err)
Close #1
End If