DIR无法正常运行

时间:2015-12-08 15:57:28

标签: excel vba excel-vba

我正在使用VBA将.txt文件中的数据导入到我用于进一步数据透视表的电子表格表中。我从中导入文件的网络目录包含~5500个文件,并且将随着时间的推移每年增加约2000个文件。表中的条目按日期排序(从最旧到最新)。

我有一个宏来检查最近一个条目的日期,然后使用DIR搜索网络位置并遍历该目录中的文件。对于每个文件,如果文件比最新条目更新,我想导入数据并将其添加到表中。如果文件较旧,我希望DIR移动到下一个文件。以下是我目前使用的代码。

Sub NewFilesFromNetwork()

Dim myDatabase As Worksheet
Set myDatabase = Sheets("Database")

Dim TotalRows As Long, LastDate As Date

TotalRows = myDatabase.ListObjects("Table1").Range.Rows.Count
LastDate = Cells(TotalRows + 48, 6).Value 'the "+48" here is important because there are 48 hidden rows at the top of the spreadsheet before the table starts

Dim MyFolder As String, MyFile As String

On Error Resume Next
Application.ScreenUpdating = False

MyFolder = "*path to my network location*" 
MyFile = Dir(MyFolder & "*.txt")

Dim t As Integer, k As Integer
t = 0 'counter for calculating total files imported
k = 0 'counter for calculating total files checked

Do While MyFile <> ""
    TxtFile = MyFolder & MyFile
    If FileDateTime(TxtFile) > LastDate Then 
        Open TxtFile For Input As #1 
        Do Until EOF(1)
            Line Input #1, textline
            text = text & textline
        Loop
        Close #1
        Call CommonImportCode 'separate sub which picks out information from the .txt file string and adds it to the table as a new entry
        k = k + 1
        t = t + 1
        MyFile = Dir()
    End If

        k = k + 1
        MyFile = Dir()
Loop

Application.ScreenUpdating = True

MsgBox "Number of files searched = " & k & vbNewLine & "Number of files imported = " & t

End Sub

我遇到的问题是:

我可以检查网络位置,看看有10个新文件。但是,宏只导入其中的5个,并且似乎只导入新文件的每个其他文件。宏在满足IF语句的条件时是否有跳过文件的原因?

1 个答案:

答案 0 :(得分:4)

    k = k + 1
    MyFile = Dir()

该代码重复。如果上面的“If”是真的,那么你正在跳过一个文件。你的循环应该是:

Do While MyFile <> ""
    TxtFile = MyFolder & MyFile
    If FileDateTime(TxtFile) > LastDate Then 
        Open TxtFile For Input As #1 
        Do Until EOF(1)
            Line Input #1, textline
            text = text & textline
        Loop
        Close #1
        Call CommonImportCode 'separate sub which picks out information from the .txt file string and adds it to the table as a new entry
        t = t + 1
    End If
    k = k + 1
    MyFile = Dir()
Loop

或接近的事情。