如何读取txt文件并将其导入访问表

时间:2019-09-30 20:22:28

标签: vba ms-access

我是初次使用vba。我正在尝试找到一种将txt文件导入到我的Access数据库中的方法。我阅读了许多文章和论坛,并测试了许多代码,但没有一个起作用。 我能够缩小到下面列出的代码。我的问题是它可以运行,然后关闭数据库并重新启动。没有错误,只是无尽的奔跑。我的txt文件不是那么大,除非我的代码中有错误并且不知道如何解决,否则它不应该这样做。 请帮忙。

Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
Dim filepath As String
Dim txtStream As Object
Dim strImportRecord As String

filepath = "\\C:\"
 FileSpec = "*.txt*"

FileName = Dir(filepath & FileSpec)

If FileName <> "" Then
    MostRecentFile = FileName
    MostRecentDate = FileDateTime(filepath & FileName)
    Do While FileName <> ""
        If FileDateTime(filepath & FileName) > MostRecentDate Then
             MostRecentFile = FileName
             MostRecentDate = FileDateTime(filepath & FileName)
        End If

       Loop
End If

Set txtStream = CreateObject("Scripting.FileSystemObject").OpenTextFile(MostRecentFile)

Do While Not (txtStream.atendofstream)
        strImportRecord = txtStream.ReadAll
  Loop

DoCmd.TransferText acImportFixed, "myspecification", "mytable", "strImportRecord", False 

2 个答案:

答案 0 :(得分:1)

尝试一下:

Sub ImportMostRecentTextFile()

Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
Dim filepath As String
Dim txtStream As Object
Dim strImportRecord As String

filepath = "C:\Users\moone2\Documents\"
 FileSpec = "*.txt*"

FileName = Dir(filepath & FileSpec)

If FileName <> "" Then
    MostRecentFile = FileName
    MostRecentDate = FileDateTime(filepath & FileName)
    Do While FileName <> ""
        If FileDateTime(filepath & FileName) > MostRecentDate Then
             MostRecentFile = FileName
             MostRecentDate = FileDateTime(filepath & FileName)
        End If
        FileName = Dir()
       Loop
End If

'I don't think you need to load the text....
'------------
'Set txtStream = CreateObject("Scripting.FileSystemObject").OpenTextFile(MostRecentFile)'
'
'Do While Not (txtStream.atendofstream)
'    strImportRecord = txtStream.ReadAll
'Loop
'
'Set txtStream = Nothing
'
'Debug.Print strImportRecord

'DoCmd.TransferText acImportFixed, "myspecification", "mytable", strImportRecord,
'---------------

'Just load from the most recent file, like this:
DoCmd.TransferText acImportFixed, "myspecification", "myTable", MostRecentFile, True

结束子

答案 1 :(得分:0)

您的循环以查找最新文件:

Do While FileName <> ""

永远不会结束,因为您永远不会在循环中为FileName分配任何新内容。

您在FileName = Dir()之前缺少Loop

这不是唯一的问题,迈克在评论中写的所有内容都是正确的。