0

我是访问 vba 的新手。我正在尝试找到一种将 txt 文件导入我的访问数据库的方法。我阅读了很多文章和论坛,测试了很多代码,但都没有奏效。我能够缩小到下面列出的代码。我遇到的问题是它运行并运行,然后我关闭了我的数据库并重新开始。没有错误,只是无尽的运行。我的 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 
4

2 回答 2

1

尝试这个:

子 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

结束子

于 2019-10-02T22:05:22.473 回答
0

您的循环查找最新文件:

Do While FileName <> ""

FileName永远不会结束,因为你永远不会在循环中分配任何新的东西。

你缺少一个FileName = Dir()before Loop

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

于 2019-09-30T21:24:07.340 回答