选择一个文件夹并从多个工作簿中复制选项卡

时间:2018-06-14 20:38:55

标签: excel-vba vba excel

我对VBA编码非常陌生,需要一个宏,首先允许我选择一个包含多个工作簿的文件夹。其中每个都只有一个选项卡,我需要将所有这些选项卡复制到一个工作簿中。我不希望所有数据都放在一张纸上。如果我里面有5个文件,我需要复制5个标签。预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

放手一搏:

它应该提示输入文件,并将目录中的所有工作表添加到您放入此宏的工作簿中。

Sub CreateSheet(worksheetname)
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = worksheetname
    End With
End Sub


Sub WorksheetLoop()

         Dim WS_Count As Integer
         Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
         WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
         For I = 1 To WS_Count

            ' Insert your code here.
            ' The following line shows how to reference a sheet within
            ' the loop by displaying the worksheet name in a dialog box.
            CreateSheet (ActiveWorkbook.Worksheets(I).Name)

         Next I

      End Sub


Sub LoopAllExcelFilesInFolder()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents
    Call WorksheetLoop
    'Change First Worksheet's Background Fill Blue
    'wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)


    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop


ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub