【问题标题】:Adding data to a specific column in a text file将数据添加到文本文件中的特定列
【发布时间】:2016-05-19 15:11:29
【问题描述】:

我想知道 Access VBA 中是否有一种方法可以打开文本文件,并将数据附加到每行末尾的特定列/空间?

基本上,我需要打开文本文件并在文件中每一行的第 300 列放置一个字符(在所有数据之后)。

我知道我可以将数据导入 Access,添加列,然后将其导出,但出于商业原因,我试图避免这种情况。

谢谢!

【问题讨论】:

标签: vba ms-access text-files


【解决方案1】:

您可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多