在vba中对齐文本文件

时间:2014-03-20 13:48:29

标签: vba excel-vba excel

我的应用程序是在vba中,我想在需要四列的文本文件中记录信息。该工具应打开日志文件并记录问题并立即关闭文件,以便并行运行的其他进程也可以将问题发布到该文件而不会丢失数据。继续附加到日志文件。此外,如果字符串对于最后一列太长,那么它应该被分成几部分,并且所有部分应该在正确对齐的情况下逐一进入最后一列。

Sub ExportToTXT()

Dim fName As String
Dim WholeLine As String
Dim FNum As Integer
Dim RowNdx As Long
Dim Widths(1 To 4) As Integer
Dim i As Integer
Dim lngR As Long

lngR = Cells(Rows.Count, 1).End(xlUp).Row

fName = ThisWorkbook.Path & "\Export Fixed width columns.txt"

On Error GoTo EndMacro:
FNum = FreeFile

'These are the desired column widths in the text file

Widths(1) = 30
Widths(2) = 40
Widths(3) = 50
Widths(4) = 80

Open fName For Append Access Write As #FNum
WholeLine = ""
WholeLine = WholeLine & Left("Value for first column" & String(Widths(1), " "), Widths(1))
WholeLine = WholeLine & Left("Value for second column" & String(Widths(2), " "), Widths(2))
WholeLine = WholeLine & Left("Value for third column" & String(Widths(3), " "), Widths(3))
WholeLine = WholeLine & Left("Value for fourth column" & String(Widths(4), " "), Widths(4))
Print #FNum, WholeLine

EndMacro:     On Error GoTo 0      关闭#FNum

End Sub

1 个答案:

答案 0 :(得分:0)

大家好我得到了解决方案,下面是我正在使用的代码 感谢你的宝贵时间。 :)

Sub WriteTo_CommonLogFile(First_30Char As String, Second_40Char As String, Third_40Char As String, Fourth_50Char As String)

Dim StrVal As String
Dim StartFrom As Long, EndUpTo As Long
Dim Limit As Double
Dim j As Long
With CreateObject("Scripting.FileSystemObject").OpenTextFile(Form_TopLevel.Txt_Bx_Error_LogFile.Value, 8, True)
        If Len(Fourth_50Char) > 50 Then
            Limit = Module5.Ceiling(Len(Fourth_50Char) / 50, 1)
            StartFrom = 1
            EndUpTo = 50
            For j = 0 To Limit - 1
                StrVal = VBA.MID$(Fourth_50Char, StartFrom, EndUpTo)

                If j = 0 Then
                    .WriteLine " "
                    .WriteLine VBA.Format(First_30Char, "!" & VBA.String(30, "@")) & VBA.Format(Second_40Char, "!" & VBA.String(40, "@")) _
                    & VBA.Format(Third_40Char, "!" & VBA.String(40, "@")) & VBA.Format(StrVal, "!" & VBA.String(50, "@"))
                Else
                    .WriteLine VBA.Space(110) & StrVal
                End If
                StartFrom = StartFrom + 50
            Next j
        Else
            .WriteLine " "
            .WriteLine VBA.Format(First_30Char, "!" & VBA.String(30, "@")) & VBA.Format(Second_40Char, "!" & VBA.String(40, "@")) _
                       & VBA.Format(Third_40Char, "!" & VBA.String(40, "@")) & VBA.Format(Fourth_50Char, "!" & VBA.String(50, "@"))
        End If
    .Close
End With
End Sub


Function Ceiling(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
' X is the value you want to round
' is the multiple to which you want to round
Ceiling = (Int(x / Factor) - (x / Factor - Int(x / Factor) > 0)) * Factor
End Function

thanx很多人......:)