Excel VBA循环消息

时间:2019-06-25 19:35:52

标签: excel vba

我刚开始编写代码。我正在使用Excel2016。

这是我要完成的工作:我有多个Excel工作簿,其中有一张纸。我正在尝试将所有这些合并为一个工作簿。

我收到错误消息

  

“编译错误:不执行循环”

欢迎任何建议和/或帮助。先感谢您。

'Description: Combines all files in a folder to a master file.

Sub MergeFiles()

    Dim path As String, ThisWB As String, lngFilecounter As Long

    Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet

    Dim Filename As String, Wkb As Workbook

    Dim CopyRng As Range, Dest As Range

    Dim RowofCopySheet As Integer

    RowofCopySheet = 2 ' Row to start on in the sheets you are copying from

    ThisWB = ActiveWorkbook.Name

    path = Environ("userprofile") & "\Desktop\TEST\"

    Application.EnableEvents = False

    Application.ScreenUpdating = False

    Set shtDest = ActiveWorkbook.Sheets(1)

    Filename = Dir(path & "\*.xls", vbNormal)

    If Len(Filename) = 0 Then Exit Sub

    Do Until Filename = vbNullString

        If Not Filename = ThisWB Then

            Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)

            Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), 

            Cells(ActiveSheet.UsedRange.Rows.Count, ActiveSheet.UsedRange.Columns.Count))

            Set Dest = shtDest.Range("A" & 

            shtDest.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1)

            CopyRng.Copy Dest

            Wkb.Close False

        End If

        Filename = Dir()

End Sub

在调试期间,它在"Sub MergeFiles()"处停止,并且不再进行任何操作。

1 个答案:

答案 0 :(得分:0)

我对您的问题进行了修改,以使其更易读,

            End If
        Filename = Dir()
    Loop                            ' <--------------- Add this statement
End Sub

Do循环需要关闭。通过缩进if语句和循环,可以更轻松地阅读程序并了解程序的运行情况。