我需要一些固定寬度格式檔案的幫助。嘗試創建具有兩個交替行的檔案格式 - 記錄型別 AA 和記錄型別 BB
輸入檔案如下所示:
輸入檔案
示例輸出檔案:
AA000022018110112345678D9SDRWSANON8602P 000005000ADSK SRO PN 0001080000000
BB0000220181101 ARPI
AA000032018110112345678D9BDRWSANON8602H 000005000ADSK SRR PN 0001080000000
BB0000320181101
寫入檔案的代碼如下;試圖找出將 & vbNewLine & 代碼放在哪里,以便將檔案分成兩行。
Sub exportBD()
Dim UsedRows As Long
Dim UsedColumns As Long
Dim lRow As Long
Dim i As Long, j As Long
Dim rng As Range
Open Environ("userprofile") & "\Dfile" & Format(Date, "mmddyy") & "." & Format(TIME, "hhmm") & ".txt" For Output As #1
With shtBD
'Header
lRow = .Range("A" & .Rows.Count).End(xlUp).row
Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, 2))
UsedRows = .UsedRange.Rows.Count
UsedColumns = .UsedRange.Columns.Count
Set Header = shtBD.Range("A2:F2")
Print #1, Join(Array(shtBD.Range("A2"), shtBD.Range("B2"), shtBD.Range("C2"), shtBD.Range("D2"), shtBD.Range("E2"), shtBD.Range("F2")))
For i = 3 To UsedRows
For j = 1 To UsedColumns - 1
Print #1, .Cells(i, j); " ";
Next j
Print #1, .Cells(i, UsedColumns)
Next i
End With
Print #1, "UTRL " & UsedRows - 2
Close #1
MsgBox "Finished...", vbInformation
End Sub
我將把 & vbNewLine 放在哪里,以便輸出顯示為兩行?我知道它在底部的“for..next”回圈內部和周圍的某個地方,但不太確定。
uj5u.com熱心網友回復:
For i = 3 To UsedRows
For j = 1 To UsedColumns - 1
' <-- you would either add it here, or within-, or after the next line:
Print #1, .Cells(i, j); " ";
Next j
Print #1, .Cells(i, UsedColumns)
Next i
但最有可能的一種更簡潔的方法是在函式頂部附近(所有其他Dim陳述句所在的位置)定義一個分隔符變數:
Dim sColumnSep as String
然后做類似的事情
For i = 3 To UsedRows
For j = 1 To UsedColumns - 1
If j = 99999 Then
sColumnSep = VbCrLf;
Else
sColumnSep = " ";
End If
Print #1, .Cells(i, j) & sColumnSep;
Next j
Print #1, .Cells(i, UsedColumns)
Next i
99999換行前最后一列的數字應該在哪里(不確定正確的值是什么,很可能是5)。
uj5u.com熱心網友回復:
謝謝你的幫助。能夠使用以下方法修復代碼:
For i = 3 To UsedRows
For j = 1 To UsedColumns - 1
If j = 39 Then
sColumnSep = vbNewLine
Else
sColumnSep = " "
End If
Print #1, .Cells(i, j) & sColumnSep;
Next j
Print #1, .Cells(i, UsedColumns) & " "
Next i
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/386816.html
