简体   繁体   中英

Copy different workbooks from an folder into different sheets in one workbook

I wrote the following code to clean the workbook and then to create empty sheets

Sub conclusion()
Dim xWs As Worksheet
Dim Path As String, Filename As String



    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each xWs In Application.ActiveWorkbook.Worksheets
        If xWs.Name <> "Sheet1" And xWs.Name <> "Summary" Then
            xWs.Delete
        End If
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    ' create new sheets

    Dim MyCell As Range, MyRange As Range

    Set MyRange = Sheets("Summary").Range("A2")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))

    For Each MyCell In MyRange
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
    Next MyCell

    ' copy the workbooks into the sheets (My question )

End Sub

and then it should read the path from a cell in my case B2 and look for all xls files in this folder and copy to the crated sheets whose names are in 范围A2

I wrote the following

 Path= Sheets("Summary").Range("B2").Value ***( it does not read the value of B2, why? )***
  Filename = Dir("Path" & "*.xls")
  Do While Filename <> ""

***here is my question, how can I write the following:
COPY THE WORKBOOK 1 INTO SHEET with the name from Cell A2*** 
  Loop

To fix the first problem try:

With Application.Workbooks("BookName").Sheets("Summary")
    Path = .Range("B1").Text & "\" & .Range("A2").Text
End With

For the second your variable Path is in quotes which it shouldn't be as it is not a string but a string variable. Not too sure why you had the wildcard asterisk in there either...

Filename = Dir(Path & ".xls")

For the last part, your For Loop is missing what it is that you want to cycle through (ie. cells)

For Each MyCell In MyRange.Cells
    Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
    Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM