Excel VBA - 导入多个xlsx工作表并附加到主工作簿表

时间:2016-04-03 04:29:02

标签: excel vba macros

我正在尝试将多个XLSX / XLS表导入到我的主工作簿的“临时”表中,每个工作簿内容都应在最后一个条目后附加。

这只适用于一个文件,但我似乎无法解决循环遍历所有选定工作簿的逻辑。另外,考虑到性能和速度,选择它们之后打开所有选定的工作簿是明智的,还是应该在导入上一个文件后打开它们?

非常感谢您的帮助。

编辑: 为了更精确一点,脚本的问题是我应该查看所有打开的工作簿的部分。建议任何人?

For Each Workbooks In lngCount

    With Workbooks
        .Sheets(1).Cells.Copy Destination:=MasterWB.Sheets("temp").Range("A65536").End(xlUp).Offset(1, 0)
        .Close False
    End With

Next

完整的VBA代码:

Sub import_XLS()
Dim wb As Workbook
Dim lngCount As Long

' speed up by turning screenupdating off
    Application.ScreenUpdating = False

' set workbooks
    Set MasterWB = ActiveWorkbook

    With ActiveWorkbook.Sheets("temp")
        .Visible = True
        .Cells.Delete
    End With

' Open the file dialog
    With Application.FileDialog(msoFileDialogOpen)
        .InitialFileName = ""
        .Title = "Please select the converted User Activity files for import"
        .Filters.Add "Excel Files", "*.xls; *.xlsx", 1
        '.Filters.Add "Excel Files", "*.xls", 1
        .AllowMultiSelect = True

        If .Show = -1 Then
             ' Open the files
            For lngCount = 1 To .SelectedItems.Count
                Workbooks.Open .SelectedItems(lngCount)
            Next lngCount

            Else
                Exit Sub
        End If

    End With

' open selected workbook in read only and copy all cells of worksheet 1

For Each Workbooks In lngCount

    With Workbooks
        .Sheets(1).Cells.Copy Destination:=MasterWB.Sheets("temp").Range("A65536").End(xlUp).Offset(1, 0)
        .Close False
    End With

Next

' hide temp sheet, close workbook without saving changes and free memory
    'MasterWB.Sheets("temp").Visible = False
    'wb.Close False
    Set wb = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

Dim wb As Workbook
....

For Each wb In Workbooks
    with wb
        if .name <>MasterWB.Name
        ....    
    end with
Next wb