EFT文件-唯一尺寸的VBA宏

时间:2019-06-26 18:07:07

标签: excel vba

我试图弄清楚如何创建具有三个单独部分的.prn文件。 1)页眉2)细节3)页脚。

我想出了detail部分的代码,它工作正常。但是,我不确定如何插入单独的页眉和页脚。

Sub Export_Selection_As_Fixed_Length_File()
     ' Dimension all  variables.
    Dim DestinationFile, CellValue, Filler_Char_To_Replace_Blanks As String
    Dim FileNum, ColumnCount, RowCount, FieldWidth As Integer
    Dim sht As Worksheet

    'Below are options incase you want to change the folder where VBA stores the .txt file
    'We use ActiveWorkbook.Path in this example
    'ActiveWorkbook.Path 'the activeworkbook
    'ThisWorkbook.Path  'the workbook with the code
    'CurDir  'the current directory (when you hit File|open)


    'If a cell is blank, what character should be used instead
    Filler_Char_To_Replace_Blanks = " "

    'Check if the user has made any selection at all
    If Selection.Cells.Count < 2 Then
        MsgBox "Nothing selected to export"
        Selection.Activate
        End
    End If

    'This is the destination file name.
    DestinationFile = ActiveWorkbook.Path & "/File_With_Fixed_Length_Fields.txt"
    'Obtain next free file handle number.
    FileNum = FreeFile()

     ' Turn  error checking off.
    On Error Resume Next

     ' Attempt to open destination file for output.
    Open DestinationFile For Output As #FileNum

     ' If an error occurs report it and end.
    If Err <> 0 Then
         MsgBox "Cannot open filename " & DestinationFile
         Selection.Activate
        End
    End If

     ' Turn error checking on.
    On Error GoTo 0

     '  Loop for each row in selection.
    For RowCount = 1 To Selection.Rows.Count
                For ColumnCount = 1 To Selection.Columns.Count
                    CellValue = Selection.Cells(RowCount, ColumnCount).Text
                    If (IsNull(CellValue) Or CellValue = "") Then CellValue = Filler_Char_To_Replace_Blanks
                    FieldWidth = Cells(1, ColumnCount).Value
                    If (ColumnCount = Selection.Columns.Count) Then
                            Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@")) & vbCrLf;
                    Else: Print #FileNum, Format$(CellValue, "!" & String(FieldWidth, "@"));
                    End If
                Next ColumnCount
         ' Start next iteration of RowCount loop.
    Next RowCount
     ' Close destination file.
    Close #FileNum
    Selection.Activate
    Workbooks.OpenText Filename:=DestinationFile
End Sub

0 个答案:

没有答案