Vba 遍历目录时发生循环错误

Vba 遍历目录时发生循环错误,vba,excel,loops,text,Vba,Excel,Loops,Text,我希望有人能帮忙。。。我有下面的代码,它一整天都在工作。直到16:10,现在突然决定接收运行时错误。在线Sheet1.单元格(最后一行,1)=数据 Sub Loopthroughtxtdir() Dim Filename As String Dim Path As String Path = "C:\MK\MasterData\" Filename = Dir(Path & "*.txt") With ThisWorkbook.Sheets("

我希望有人能帮忙。。。我有下面的代码,它一整天都在工作。直到16:10,现在突然决定接收运行时错误。在线
Sheet1.单元格(最后一行,1)=数据

Sub Loopthroughtxtdir()
    Dim Filename As String
    Dim Path As String

    Path = "C:\MK\MasterData\"
    Filename = Dir(Path & "*.txt")

    With ThisWorkbook.Sheets("Sheet1")
        Dim lastRow As Long
        lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
        Do While Len(Filename) > 0
            Dim handle As Integer
            handle = FreeFile
            Open Path & Filename For Input As #handle
            Do Until EOF(handle)
                Line Input #handle, Data
                Sheet1.Cells(lastRow, 1) = Data
                lastRow = lastRow + 1
            Loop
            Close #handle
            Filename = Dir
        Loop
    End With

    MsgBox ("Import Complete")

End Sub

谁能帮忙吗。我很不明白为什么会这样。没有任何更改,经过几次测试后,现在已停止。

正如注释中指出的,您的行数已用完。一种解决方案是测试您是否刚刚到达最后一行,然后继续新的工作表(显然未经测试,但应给出要点):


运行时错误是什么?@A.S.H我只有在进入“立即”和?Sheet1.Cells(lastRow,1)=数据时才会得到运行时错误运行时是1004应用程序定义的或对象定义的错误在立即窗口中键入
?数据
,你得到了什么?(首先在该行上放置一个断点,并在即时窗口中检查
Data
的值)。无响应请记住,您将受到行数的限制
1048576
是Excel在单个工作表中可以接受的最大行数。
Sub Loopthroughtxtdir()
    Dim Filename As String
    Dim Path As String

    Path = "C:\MK\MasterData\"
    Filename = Dir$(Path & "*.txt")

    Dim currentSheet As Worksheet
    Set currentSheet = ThisWorkbook.Worksheets("Sheet1")
    With currentSheet
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    End With

    Do While Len(Filename) > 0
        Dim handle As Integer
        handle = FreeFile
        Open Path & Filename For Input As #handle
        Do Until EOF(handle)
            Line Input #handle, Data
            currentSheet.Cells(lastRow, 1) = Data
            lastRow = lastRow + 1
            If lastRow > currentSheet.Rows.Count Then
                Set currentSheet = ThisWorkbook.Worksheets.Add
                lastRow = 1
            End If
        Loop
        Close #handle
        Filename = Dir$
    Loop

    MsgBox ("Import Complete")
End Sub