2016-05-19 7 views
0

Мне было интересно, есть ли способ в Access VBA открыть текстовый файл и добавить данные в конец каждой строки в определенном столбце/пробеле?Добавление данных в определенный столбец в текстовом файле

В принципе, мне нужно открыть текстовый файл и поместить символ в столбец № 300 каждой строки в файле (который является после всех данных).

Я знаю, что могу просто импортировать данные в Access, добавить столбец, а затем экспортировать его, но по причинам бизнеса я стараюсь избегать этого.

Спасибо!

+0

Да, это возможно. http://stackoverflow.com/questions/36270732/vba-code-to-open-text-file поможет вам начать чтение текстового файла. Если вы столкнетесь с помехами, разместите свой код, и мы поможем вам его отладить. – Tim

+0

Спасибо, сэр! – Jim

ответ

0

Вы можете выполнить это, используя библиотеку Runtime Microsoft Scripting. Добавьте ссылку на эту библиотеку в свой проект 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 
Смежные вопросы