如何使用VBA将100个工作簿合并到主工作簿中?

时间:2018-02-12 03:59:13

标签: excel excel-vba vba

这是尝试这样做的:

Sub GetSheets()

Dim Path As Variant
Dim filename As Variant
Dim sheet As Variant

Path = "C:\Users\Asus\Google Drive\Income Generating\Stock Market\Daily Quotes\PSEGet"
filename = Dir(Path & "\*.csv")
  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

按下“运行宏”按钮时,将识别文件路径,但复制数据行不起作用。出现此错误:

Error Error

这些是我想要合并到主工作表中的文件。位于一个文件夹中: Directory

我想要合并的文件显示在这里: Sample of CSV file

1 个答案:

答案 0 :(得分:0)

我提出了一个有效的解决方案:

Option Explicit
Sub GetSheets()

Dim Path As Variant
Dim filename As Variant
Dim sheet As Variant
Dim Total_rows_active As Long
Dim Total_rows_compiled As Long

Application.DisplayAlerts = False

Path = "C:\Users\Asus\Google Drive\Income Generating\Stock Market\Daily Quotes\PSEGet\"
filename = Dir(Path & "\*.csv")
    Do While filename <> ""
    Total_rows_compiled = Workbooks("Compiled Stock Quotes.xlsx").Worksheets("Compiled").Range("A" & Rows.Count).End(xlUp).Row
    Workbooks.Open filename:=Path & filename, ReadOnly:=True
    Total_rows_active = Workbooks(filename).Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
    Workbooks(filename).Sheets(1).Range("A1:G" & Total_rows_active).Copy
    Workbooks("Compiled Stock Quotes.xlsx").Worksheets("Compiled").Range("A" & Total_rows_compiled + 1, "G" & Total_rows_compiled + Total_rows_active).PasteSpecial xlPasteAll
    Workbooks(filename).Close
    filename = Dir()
  Loop

代码的输出在这里:Compiled File