2017-04-26 33 views
0

これはプログラムの出力です。エクセルvbaから固定長のテキストファイルを書き込む

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

はいを​​生成されたコードを投稿してください。更新しました。参照してください –

答えて

0

何か作業をする必要があります:

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

次に、xは14スペース、xは

a = "    9983.54" 

ここで、21は必要な列の幅です。必要に応じて変更します。 CStrは、非数値のxに対しては不要です。

あなたは右詰め、あなたが一般的な目的関数を書くことができます異なる幅のフィールドに異なるデータをたくさんするつもりなら:

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))を計算します。

関連する問題