我需要使用 MS Access 读取 .txt 文件,修改记录并添加标题记录

问题描述

我有一个 .txt 文件,其中的记录在属性之间以制表符分隔。
基本上看起来像这样:

1234567898765432123456  Charleston  2021-03-17 07:25:31
23456789876543212345  Baltimore  2021-03-17 07:26:32

我需要:

  1. 添加标题记录(如果可能,包括详细记录的数量?)
  2. 在记录的开头添加一个识别字符“DR”
  3. 使记录固定长度属性,而不是制表符分隔
  4. 重新格式化日期/时间以去掉破折号和冒号

更新为如下所示:

HeaderRecordNbr001 DetailRecordCnt00002
DR1234567898765432123456 Charleston     DT20210317072531
DR23456789876543212345   Baltimore      DT20210317072632

我创建了两个进程。第一个将数据导入 Access 并进行一些转换:

Dim fileNum As Integer
Dim dataLine As String
Dim column1 As String
Dim column2 As String
Dim column3 As String
Dim column4 As String
Dim column5 As String
Dim column6 As String
Dim column7 As String
Dim column8 As String
Dim column9 As String
Dim column10 As String


fileNum = FreeFile()
ReportPath = Application.CurrentProject.Path & "\FilePickup\"
FileName = ReportPath & "testfile " & Format(Date,"yyyymmdd ") & "001" & ".txt"
DBEngine(0)(0).Execute "DELETE FROM MyTable"
Open FileName For Input As #fileNum

While Not EOF(fileNum)
    Line Input #fileNum,dataLine
    If Len(dataLine) > 1 Then
        column1 = "DR"
        column2 = Mid(dataLine,1,22)
        column3 = Mid(dataLine,24,10)
        column4 = "DT"
        column5 = Mid(dataLine,36,4)
        column6 = Mid(dataLine,41,2)
        column7 = Mid(dataLine,44,2)
        column8 = Mid(dataLine,47,2)
        column9 = Mid(dataLine,50,2)
        column10 = Mid(dataLine,53,2)
        CurrentDb.Execute "INSERT INTO MyTable(column1,column2,column3,Column4,Column5,Column6,Column7,Column8,Column9,Column10) VALUES('" & column1 & "','" & column2 & "','" & column3 & "','" & column4 & "','" & column5 & "','" & column6 & "','" & column7 & "','" & column8 & "','" & column9 & "','" & column10 & "')"
    End If
Wend

Close #fileNum

导出回 .txt 文件的第二个过程,添加标题记录。但是我无法获取标题记录以使用日期变量,或获取实际的详细记录计数。任何帮助将不胜感激?

Const VB_FORREADING = 1
Const VB_FORWRITING = 2
Const cstrFile As String = "C:\Users\Documents\Access\Reports\UpdatedFileOutput.txt"
Const cstrHeaderRow As String = "HeaderRecord202103181606   0000000010301            "
Dim oFSO As Object
Dim oFile As Object
Dim strContents As String

' do TransferText without the field names '
' (HasFieldNames default = False) '
DoCmd.TransferText acExportFixed,"Export_Specification",_
    "Record_Stg",cstrFile

Set oFSO = CreateObject("Scripting.FileSystemObject")
' read file content into strContents string variable '
Set oFile = oFSO.OpenTextFile(cstrFile,VB_FORREADING)
strContents = oFile.ReadAll
oFile.Close
' re-write file using cstrHeaderRow plus strContents '
Set oFile = oFSO.OpenTextFile(cstrFile,VB_FORWRITING)
oFile.Write cstrHeaderRow & vbCrLf & strContents
oFile.Close

Set oFile = nothing
Set oFSO = nothing

解决方法

我不会为此使用表格,仅使用字符串会更容易和更快。

您缺少一些关键要素,特别是 Split() 和 Format() 函数。
我将概述我将如何做(空气代码):

while drawIndexV < 2: