簡體   English   中英

將文件夾中的不同工作簿復制到一個工作簿中的不同工作表中

[英]Copy different workbooks from an folder into different sheets in one workbook

我編寫了以下代碼來清理工作簿,然后創建空白表

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

然后它應該從我的案例B2中的一個單元中讀取路徑,並在此文件夾中查找所有xls文件,然后復制到名稱位於 范圍A2

我寫了以下

 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

要解決第一個問題,請嘗試:

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

對於第二個變量, Path應該用引號引起來,因為它不是字符串,而是字符串變量。 不太確定為什么在其中也有通配符星號...

Filename = Dir(Path & ".xls")

對於最后一部分,您的For Loop缺少要循環的內容(即單元格)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM