フィールド名も書き出す

スポンサーリンク
スポンサーリンク

フィールド名も書き出す

Sub テキストファイルに書き込む2()
'フィールド名も書き出す
Dim myCon As New ADODB.Connection, myRS As New ADODB.Recordset
Dim myExcelFile As String, myTbl As String, myTxtFile As String
Dim tmpFldArray() As String, i As Integer

'データのあるExcelファイル
myExcelFile = ThisWorkbook.Path & "\xls\DataBook.xls"
'書き出すデータ
myTbl = "select * from [伝票一覧$] where 担当者 = '増田';"
'テキストファイル名
myTxtFile = ThisWorkbook.Path & "\txt\増田担当一覧フィールド名付.csv"

'エクセルに接続
With myCon
  .Provider = "Microsoft.Jet.OLEDB.4.0"
  .Properties("Extended Properties") = "Excel 8.0"
  .Open myExcelFile
End With

'レコードセットオブジェクトにテキストファイルの内容を格納
myRS.Open myTbl, myCon

ReDim tmpFldArray(myRS.Fields.Count - 1)
For i = 0 To UBound(tmpFldArray)
  tmpFldArray(i) = myRS.Fields(i).Name
Next

'テキストファイルに書き出し
Open myTxtFile For Output As #1
  Print #1, Join(tmpFldArray, ",")
  Print #1, myRS.GetString(adClipString, , ",", vbCrLf)
Close #1

myRS.Close: Set myRS = Nothing
myCon.Close: Set myCon = Nothing

End Sub

フィールド名はいったん配列に格納し、Join関数を使用して1つの文字列に変換してから出力している。

Join 関数
Join(sourcearray [, delimiter])

引数
指定項目 説明
sourcearray 必ず指定します。結合する文字列を含む 1次元配列を指定します。
delimiter 省略可能です。戻り値となる文字列を区切るのに使用する文字を指定します。省略すると、スペース(" ") が使用されます。引数 delimiterが長さ 0 の文字列 ("")である場合は、リスト内のすべての項目が区切り文字なしで連結されます。

元となるエクセルのデータ

実行結果

スポンサーリンク
シェアする
スポンサーリンク
あんとんさんち 覚え書き