简体   繁体   English

在Access VBA中解析txt文件

[英]Parsing txt file in Access VBA

I have never used Access VBA, but I need to create a module that parses a txt file and then immediately imports it into a table. 我从未使用过Access VBA,但我需要创建一个模块来解析txt文件,然后立即将其导入表中。

A dumbed-down of the txt is this: txt的摘要如下:

15686541

468469

48978965

456287

48666545

45684651

456788

I need to parse it in order to 我需要解析它以便

  1. Remove all the line/rows that are not six characters long 删除所有长度不超过六个字符的行/行
  2. Add commas after the third and fifth characters 在第三个和第五个字符后添加逗号

The final result being something like: 最终结果是这样的:

468,46,9

456,28,7

456,78,8

All this must be done in an Access VBA module so that the importing process becomes seamless. 所有这些都必须在Access VBA模块中完成,以便导入过程变得无缝。

Thanks a lot! 非常感谢!

Sorry to bother 抱歉打扰

This function will do that - and very fast: 此函数可以做到这一点-而且非常快:

Public Function ImportLog(ByVal Filename As String) As Long

    Dim rs      As DAO.Recordset

    Dim File    As Integer
    Dim Data    As String
    Dim Data6   As String
    Dim Records As Long

    Set rs = CurrentDb.OpenRecordset("Select Top 1 * From YourTableName")

    File = FreeFile()
    Open Filename For Input As #File

    While Not EOF(File)
        Line Input #File, Data
        If Len(Data) = 6 Then
            Data6 = Space(6 + 2) ' Space for six digits and two commas.
            ' Build field value.
            Mid(Data6, 1, 3) = Mid(Data, 1, 3)
            Mid(Data6, 4, 1) = ","
            Mid(Data6, 5, 2) = Mid(Data, 4, 2)
            Mid(Data6, 7, 1) = ","
            Mid(Data6, 8, 1) = Mid(Data, 6, 1)
            rs.AddNew
                ' Adjust "Data" to your field name.
                rs.Fields("Data").Value = Data6  
            rs.Update
            Records = Records + 1
        End If
    Wend
    Close #File
    rs.Close

    Set rs = Nothing

    ImportLog = Records

End Function

The return value is the count of added records. 返回值是已添加记录的计数。

Try this: 尝试这个:

Sub Import()
    Dim fileNum As Integer
    Dim dataLine As String
    Dim column1 As String
    Dim column2 As String
    Dim column3 As String

    fileNum = FreeFile()
    Open "Filename.txt" For Input As #fileNum

    While Not EOF(fileNum)
        Line Input #fileNum, dataLine
        If Len(dataLine) = 6 Then
            column1 = Mid(dataLine, 1, 3)
            column2 = Mid(dataLine, 4, 2)
            column3 = Mid(dataLine, 6, 1)
            CurrentDb.Execute "INSERT INTO YourTable(Column1, Column2, Column3) VALUES('" & column1 & "', '" & column2 & "', '" & column3 & "')"
        End If
    Wend

    Close #fileNum
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM