2016-05-19 12 views
0

Access VBAでテキストファイルを開き、各行の最後、特定の列/スペースにデータを追加する方法があるのだろうか?テキストファイルの特定の列にデータを追加する

基本的には、テキストファイルを開き、ファイル内の各行の#300行目に文字を配置する必要があります(すべてのデータの後ろにあります)。

私はAccessにデータをインポートして列を追加してからエクスポートすることができますが、ビジネス上の理由からこれを避けようとしています。

ありがとうございます!

+0

はい、可能です。 http://stackoverflow.com/questions/36270732/vba-code-to-open-text-fileでは、テキストファイルの読み込みが始まります。あなたが混雑している場合は、あなたのコードを投稿してください、そして私たちはそれをデバッグするのを手伝ってくれます。 – Tim

+0

ありがとうございました! – Jim

答えて

0

これは、Microsoft Scripting Runtimeライブラリを使用して実行できます。そのライブラリへの参照をVBAプロジェクトに追加します。

ここでは、テキストファイルの各レコードの末尾に区切り文字(サンプルにカンマを使用しています)を追加する手順を示します。

Private Const DELIMITER As String = "," 'this is the text file delimiter that will add a column 
Private Const FILE_PATH As String = "C:\temp\" 'this is the directory where the text file resides 

Private Sub AppendColumnToTextFile() 

    Dim fso As New FileSystemObject 
    Dim readStream As Scripting.TextStream 
    Dim writeStream As Scripting.TextStream 

    'this is the name of the text file that needs a column appended 
    Dim currentFile As String: currentFile = "Test.csv" 

    'this is a temp text file where we'll re-write each record with an additional column 
    Dim tempFile As String: tempFile = "Test.New.csv" 

    'set the read/write streams 
    Set readStream = fso.OpenTextFile(FILE_PATH & currentFile, ForReading) 
    Set writeStream = fso.OpenTextFile(FILE_PATH & tempFile, ForWriting, True) 

    'read each line of the text file, and add a deilimeter at the end 
    Do While Not readStream.AtEndOfStream 
     writeStream.WriteLine readStream.ReadLine & DELIMITER 
    Loop 

    'close the streams 
    readStream.Close 
    writeStream.Close 

    fso.CopyFile FILE_PATH & tempFile, FILE_PATH & currentFile, True 'copy the temp file to the original file path 
    Kill FILE_PATH & tempFile 'delete the temp file 

    Set writeStream = Nothing 
    Set appendStream = Nothing 
    Set fso = Nothing 

End Sub 
関連する問題