Merging workbooks into a master workbook with sepe

2019-08-18 16:25发布

I have 30 xlsx files in a folder and I want the first sheet of all that files to be merged to a new workbook. The thing is I don't want the macro to copy paste the value in to the same sheet of the new master sheet like Ron's excel merge tool does. I want a macro to create new 30 sheets on the master file and copy the data from source files. And I want the newly added sheets to be renamed as the source file name. I searched the forums for hours and found the below code. This works well except the sheet renaming thing. Can someone please look into the code and please help me to add sheet rename part to the code?

Sub Merge2MultiSheets()
    Dim wbDst As Workbook
    Dim wbSrc As Workbook
    Dim wsSrc As Worksheet
    Dim MyPath As String
    Dim strFileName As String

    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    MyPath = "C:\Jude" ' change to suit
    Set wbDst = Workbooks.Add(xlWBATWorksheet)
    strFileName = Dir(MyPath & "\*.xlsx", vbNormal)

    If Len(strFileName) = 0 Then Exit Sub

    Do Until strFileName = ""

            Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFileName)

            Set wsSrc = wbSrc.Worksheets(1)

            wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)

           wbSrc.Close False

        strFileName = Dir()

    Loop
    wbDst.Worksheets(1).Delete

    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub

1条回答
Summer. ? 凉城
2楼-- · 2019-08-18 17:12
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)

wbDst.Worksheets(wbDst.Worksheets.Count).Name = strFileName

If you want to include the path then you'll need to remove the backslash '\' and any other invalid sheet-name characters.

Make sure the name does not contain any of the following characters: : \ / ? * [ or ]

查看更多
登录 后发表回答