項目

固定長ファイルの書込

概要

構造体変数に出力するデータを代入して、バイナリで構造体変数を出力。

Option Compare Database
Option Explicit

'【固定長ファイルの仕様】
'-----------+------------+------+------+------+
'  項目名   |    属性    | 桁数 | 開始 | 終了 |
'-----------+------------+------+------+------+
'   ID     |  X(3)      |   3  |    1 |    3 |
'-----------+------------+------+------+------+
'   商品名  |  X(10)     |  10  |    4 |   13 |
'-----------+------------+------+------+------+
'   数量    | -9(4).9(2) |   8  |   14 |   21 |
'-----------+------------+------+------+------+
'   単価    |  9(5)      |   5  |   22 |   26 |
'-----------+------------+------+------+------+

'--------------------------------------------------------------
' 構造体定義領域
'--------------------------------------------------------------
Private Type testStructure
    ID        As String * 3
    itemName  As String * 10
    suryo     As String * 8
    tanka     As String * 5
End Type

'--------------------------------------------------------
' 名称    : writeFixedFile
'
' 機能    : 固定長ファイルの書込
'--------------------------------------------------------
Sub writeFixedFile()

  Dim filePath     As String
  Dim fileNumber   As Long
  Dim i            As Long
  Dim tStructure(2) As testStructure
  
  '出力するデータを構造体配列に格納
  With tStructure(0)
    .ID = "004"
    .itemName = "item4"
    .suryo = Format(-10, "00000.00;-0000.00")
    .tanka = Format(500, "00000")
  End With
  With tStructure(1)
    .ID = "005"
    .itemName = "item5"
    .suryo = Format(250.15, "00000.00;-0000.00")
    .tanka = Format(15, "00000")
  End With
  With tStructure(2)
    .ID = "006"
    .itemName = "item6"
    .suryo = Format(100, "00000.00;-0000.00")
    .tanka = Format(150, "00000")
  End With
  
  '出力するファイル
  filePath = "E:\temp\tes_out.txt"
  'ファイル有無確認(あったら削除)
  If Dir(filePath) <> "" Then Kill filePath
  'ファイルハンドル
  fileNumber = FreeFile
  'オープン
  Open filePath For Binary As #fileNumber
  'テーブル処理
  For i = 0 To UBound(tStructure)
    Put #fileNumber, , tStructure(i)  'データ書込(構造体指定)
    Put #fileNumber, , vbCrLf         '改行書込
  Next
  'クローズ
  Close #fileNumber

'【tes_out.txt】
'004item4     -0010.0000500
'005item5     00250.1500015
'006item6     00100.0000150

End Sub