从excel vba编写固定宽度的文本文件

时间:2017-04-26 15:34:35

标签: vba excel-vba excel

这是程序的输出。

Current Output of my program

我已经指定了程序中每个单元格的宽度,我的程序显示正确的输出。

我想要做的是细胞内容应该从右到左书写。例如,突出显示的图9983.54的宽度为21.文本文件使用了前7列。但我希望它使用最后7列的文本文件。

请参阅预期的输出图像。

Expected output

我没有得到任何线索如何做到这一点。我不是一个非常专业的程序员,但我喜欢编码。此文本文件用作其他程序的输入,我试图自动从excel VBA写入文本文件。

有人可以建议一种获取此输出格式的方法吗?

这是给我第一个输出的代码

Option Explicit

Sub CreateFixedWidthFile(strFile As String, ws As Worksheet, s() As Integer)
    Dim i As Long, j As Long
    Dim strLine As String, strCell As String

    'get a freefile
    Dim fNum As Long
    fNum = FreeFile

    'open the textfile
    Open strFile For Output As fNum
    'loop from first to last row
    'use 2 rather than 1 to ignore header row
    For i = 1 To ws.Range("a65536").End(xlUp).Row
        'new line
        strLine = ""
        'loop through each field
        For j = 0 To UBound(s)
            'make sure we only take chars up to length of field (may want to output some sort of error if it is longer than field)
            strCell = Left$(ws.Cells(i, j + 1).Value, s(j))
            'add on string of spaces with length equal to the difference in length between field length and value length
            strLine = strLine & strCell & String$(s(j) - Len(strCell), Chr$(32))
        Next j
        'write the line to the file
        Print #fNum, strLine
    Next i
    'close the file
    Close #fNum

End Sub

'例如可以使用以下代码调用代码:

Sub CreateFile()
    Dim sPath As String
    sPath = Application.GetSaveAsFilename("", "Text Files,*.txt")
    If LCase$(sPath) = "false" Then Exit Sub
    'specify the widths of our fields
    'the number of columns is the number specified in the line below +1
    Dim s(6) As Integer
    'starting at 0 specify the width of each column
    s(0) = 21
    s(1) = 9
    s(2) = 15
    s(3) = 11
    s(4) = 12
    s(5) = 10
    s(6) = 186
    'for example to use 3 columns with field of length 5, 10 and 15 you would use:
    'dim s(2) as Integer
    's(0)=5
    's(1)=10
    's(2)=15
    'write to file the data from the activesheet
    CreateFixedWidthFile sPath, ActiveSheet, s
End Sub

1 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

x = 9983.54
a = Space(21-Len(CStr(x))) & CStr(x)

然后a将是14个空格,后跟x:

a = "              9983.54"

这里21是所需的列宽---根据需要改变。非数字x可能不需要CStr

如果您要将大量不同数据右对齐到不同的宽度字段,您可以编写一个通用函数:

Function LeftJust(val As String, width As Integer) As String
    LeftJust = Space(width - Len(val)) & val
End Function

您使用LeftJust(CStr(9983.54), 21)调用它。

另请注意,VBA的Print #语句具有Spc(n)参数,您可以使用该参数来生成固定宽度输出,例如Print #fNum, Spc(n); a;在此声明之前,您计算n:n = 21-Len(CStr(a))

希望有所帮助