每次运行时,我的VBA代码都会导致Excel崩溃

时间:2018-06-11 15:18:51

标签: excel vba excel-vba

有没有人知道每次运行宏时哪些行或代码行会导致Excel崩溃?当我从另一个工作簿中注释掉复制并粘贴到当前工作簿时,它运行正常,所以我猜它与这些行有关,但我不明白为什么复制和粘贴会导致它崩溃。 ..

代码应该遍历特定于.xlsb文件类型的文件夹中的所有文件,并从该.xlsb文件中复制选择并将其粘贴到当前的.xlsm文件中。

Option Explicit

Sub OpenFiles()

    Dim objFs As Object
    Dim objFolder As Object
    Dim file As Object

    Set objFs = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFs.GetFolder(Application.ThisWorkbook.Path)

    Dim lastCol As Integer
    lastCol = 2

    For Each file In objFolder.Files
        If file Like "*.xlsb" Then

            Dim src As Workbook
            Set src = Workbooks.Open(file.Path, True, True)

            src.Worksheets("Rates").Range("C5", "C29").Copy
            ThisWorkbook.Worksheets("Sheet4").Cells(3, lastCol).PasteSpecial xlPasteValues

            src.Close False
            Set src = Nothing
            lastCol = lastCol + 1
        End If
    Next
End Sub

1 个答案:

答案 0 :(得分:3)

将Dim取出循环,检查以确保您没有尝试重新打开ThisWorkbook并传输值而不是使用剪贴板进行复制。

...
Dim src As Workbook

For Each file In objFolder.Files
    If file Like "*.xlsb" and file not like ThisWorkbook.name Then

        Set src = Workbooks.Open(file.Path, UpdateLinks:=True, readonly:=True)

        with src.Worksheets("Rates").Range("C5:C29")
            ThisWorkbook.Worksheets("Sheet4").Cells(3, lastCol).resize(.rows.count, .columns.count) = .value
        end with

        src.Close False
        Set src = Nothing
        lastCol = lastCol + 1
    End If
Next file
...