You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过VBA写入日志文件时去除每行开头的多余空格

解决VBA错误日志开头多出14个空格的问题

你的代码里每行开头自动多出14个空格,问题出在Print #fNum, , eRecord这行的第二个逗号上。VBA的Print语句中,逗号是用来指定输出的列位置,默认每段间隔14列,第二个逗号会强制内容从第14列开始输出,前面自然就补了14个空格。

修复方法

把所有Print #fNum, , eRecord改成Print #fNum, eRecord(去掉中间的逗号)即可。修改后的完整代码如下:

Sub LogError(ByVal eCode As String, ByVal eDesc As String, ByVal eSource As String, ByVal eSub As String)
'                  Error Number           Error Description      Error Source             Sub/Function Error Occurred In
    Dim fNum As Integer
    Dim fName As String
    Dim eRecord As String
        eRecord = "Date: " & Date & " # User: " & Environ("Username") & " # System: " & Environ("ComputerName") & _
                    " # Error Code: " & eCode & " # Descripton: " & eDesc & " # Source: " & eSource & " # Calling Routine: " & eSub
        fName = Environ("Temp") & "\TDB_Error_" & Replace(CStr(Date), "/", "_") & ".log"
        Select Case Dir(fName)
            Case ""
                fNum = FreeFile()
                Open fName For Output As fNum
                Print #fNum, eRecord
                Close #fNum
            Case Else
                fNum = FreeFile()
                Open fName For Append As fNum
                Print #fNum, eRecord
                Close #fNum
        End Select
End Sub

补充说明

你之前尝试的其他方法之所以不符合需求:

  • Binary Access Write配合Put会自动在字符串前添加长度标识,导致日志内容异常;
  • Write #方法会给输出的字符串自动加上引号,还会处理分隔符,不符合日志的格式要求;
  • 修改后的Print语句既不会添加多余空格和引号,还能自动换行,完全满足错误日志的写入需求。

内容的提问来源于stack exchange,提问作者Glenn G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:40:30