2017-07-19 103 views
1

我从来没有使用过Access VBA,但我需要创建一个模块来解析txt文件,然后立即将它导入到表中。在Access VBA中解析txt文件

的TXT的简单化下是这样的:

15686541 

468469 

48978965 

456287 

48666545 

45684651 

456788 

我需要为了解析它

  1. 删除所有行/行不六个字符
  2. 在第三个和第五个字符后加逗号

最终的结果是类似于:

468,46,9 

456,28,7 

456,78,8 

所有这些都必须在Access VBA模块中完成,以便导入过程变得无缝。

非常感谢!

很抱歉打扰

+1

我建议将文本文件导入到临时表中,然后可以轻松地通过一个SQL查询完成所有转换。它会比使用VBA循环记录更快地工作。 –

回答

2

此功能会做到这一点 - 而且速度非常快:

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 

返回值是添加记录的计数。

+1

[Mid Statement](https://msdn.microsoft.com/zh-cn/vba/language-reference-vba/articles/mid-statement)。该死的。这是否永远存在?我从来没有注意到这一点,只有看似相关的'LSet'和'RSet'。 – Andre

+1

是的,它非常古老。而且速度也非常快。对于小字符串来说,这并不重要,但对于大字符串xx K,如果可以避免并置,则会产生很大的差异。另外,代码通常更清晰(=更易于阅读)。 – Gustav

+0

*更容易阅读*,但只有在阅读'Mid(Data6,1,3)= Mid(Data,1,3)':)时才能通过WTF'“ – Andre

0

试试这个:

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