仅将第一张多个工作簿合并为一个excel vba

时间:2016-09-06 07:58:47

标签: vba excel-vba macros excel

我有一个宏可以将不同的工作簿合并到一个主Excel工作簿中:

Sub GetSheets()
Path = "\Users\myname\Documenten\Test\"
Filename = Dir(Path & "*.xls")
  Do While Filename <> ""
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
     For Each Sheet In ActiveWorkbook.Sheets
     Sheet.Copy After:=ThisWorkbook.Sheets(1)
  Next Sheet
     Workbooks(Filename).Close
     Filename = Dir()
  Loop
End Sub

我有两个问题:

  • 我想只将每个工作簿的第一个工作表包含在主工作簿中,这怎么可能?
  • 我想重命名第一个工作表,我包括工作表来自的工作簿的名称。我怎么能这样做?

非常感谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

Option Explicit

Sub GetSheets()
    Dim Path As String, fileName As String
    Dim Sht As Worksheet

    Path = "\Users\myname\Documenten\Test\"
    fileName = Dir(Path & "*.xls")
    Do While fileName <> ""
        Workbooks.Open fileName:=Path & fileName, ReadOnly:=True
        With ActiveWorkbook
            .Worksheets(1).Copy After:=ThisWorkbook.Sheets(1)
            ThisWorkbook.Sheets(2).name = .name
        End With
        ActiveWorkbook.Close
        fileName = Dir()
    Loop
End Sub

答案 1 :(得分:0)

Sub GetSheets()     昏暗的路径作为字符串,文件名作为字符串     昏暗工作表

Path = "\somepath\"
fileName = Dir(Path & "*.xls")
Do While fileName <> ""
    Workbooks.Open fileName:=Path & fileName, ReadOnly:=True
    With ActiveWorkbook
        .Worksheets(1).Copy After:=ThisWorkbook.Sheets(1)
    End With
 Workbooks(fileName).Close
    fileName = Dir()
Loop

结束子