【问题标题】:How to write the contents of the Immediate Window to a text file如何将即时窗口的内容写入文本文件
【发布时间】:2014-03-11 10:14:21
【问题描述】:

我对@9​​87654321@ 很陌生。我在

上搜索了很多,但还是不明白。

这是我的示例代码:

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)

【问题讨论】:

  • 我认为你做不到。您应该将字符串存储在一个变量中,并将该变量的内容输出到您的文本文件中。
  • 您正在寻找类似this 的东西?

标签: vba immediate-window


【解决方案1】:

可以基于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

【讨论】:

    【解决方案2】:

    对于 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
    

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2020-06-30
      • 2011-03-05
      • 2014-04-07
      • 2014-02-28
      相关资源
      最近更新 更多