将Excel 97-2003工作表导入活动工作簿

时间:2019-03-20 11:55:38

标签: excel vba

以下代码将定义路径中的Excel文件(“ .xlsx”)导入到我的活动工作簿中。

Sub GetSheets1()

    Application.ScreenUpdating = False

    Dim fPath As String, fName As String
    Dim destWB As Workbook, currentWB As Workbook
    Dim i As Long

    Set destWB = ActiveWorkbook
    fPath = "C:\Users\francisca.cambra\Dropbox\Faculdade\Thesis\MS-Project\MacroTest\"
    fName = Dir(fPath & "*.xlsx")
    Do While fName <> ""
        Set currentWB = Workbooks.Open(Filename:=fPath & fName, ReadOnly:=True)
        For i = 1 To currentWB.Sheets.Count
            currentWB.Sheets(i).Copy After:=destWB.Sheets(destWB.Sheets.Count)
        Next i
        currentWB.Close SaveChanges:=False
        fName = Dir()
    Loop

    Application.ScreenUpdating = True
    Sheets("Sheet1").Select

End Sub

对于Excel 97-2003文件,当我将fName = Dir(fPath & "*.xlsx")更改为fName = Dir(fPath & "*.xls")时,工作簿将变为空,没有宏和数据。

当我在currentWB.Close SaveChanges:=False行中注释时,宏将导入Excel 97-2003文件,并且它将复制它获得的第一个Excel工作簿两次。我认为currentWB曾经是ActiveBook,并且当运行宏时,ActiveBook是关闭的,但是我不知道为什么,因为ActiveBook具有与其他扩展不同的扩展名,因此循环不应存储ActiveBook。 / p>

1 个答案:

答案 0 :(得分:0)

已解决:)

Sub GetSheets1()

    Application.ScreenUpdating = False

    Dim fPath As String, fName As String
    Dim destWB As Workbook, currentWB As Workbook
    Dim i As Long

    Set destWB = ActiveWorkbook
    fPath = "C:\Users\francisca.cambra\Dropbox\Faculdade\Thesis\MS-Project\MacroTest\"
    fName = Dir(fPath & "*.xls")
    Do While fName <> ""
        If fName <> "Blank.xlsm.xlsm" Then
            Set currentWB = Workbooks.Open(Filename:=fPath & fName)
            For i = 1 To currentWB.Sheets.Count
                currentWB.Sheets(i).Copy After:=destWB.Sheets(destWB.Sheets.Count)
            Next i
            currentWB.Close SaveChanges:=False
        End If
        fName = Dir()
    Loop

    Application.ScreenUpdating = True
    Sheets("Sheet1").Select

End Sub