我试图使用VBA将数据从多个工作簿复制到主文件,而不知道每个工作簿的名称

时间:2016-07-12 19:43:31

标签: excel-vba vba excel

警告业余编码员......

我已经在使用此代码打开特定文件路径中的所有工作簿

Sub OpenFiles()

Dim MyFolder As String
Dim MyFile As String
MyFolder = InputBox("Please enter the folder for files")
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
MyFile = Dir
Loop
End Sub

我的下一步是尝试使用代码将打开和粘贴的工作簿中的数据复制到工作簿中,但不确定如何。问题是每次可能会打开1-3个可能的工作簿。它永远不会是同一个名字

提前致谢

1 个答案:

答案 0 :(得分:1)

Sub OpenFiles()

    Dim MyFolder As String
    Dim MyFile As String, wb As WorkBook

    MyFolder = InputBox("Please enter the folder for files")
    MyFile = Dir(MyFolder & "\*.xlsx")

    Do While MyFile <> ""

        Set wb = Workbooks.Open(Filename:=MyFolder & "\" & MyFile)

        wb.Sheets(1).Range("A1").CurrentRegion.Copy _
            ThisWorkbook.Sheets("Data").Cells(rows.Count, 1).End(xlUp).Offset(1,0)
        wb.Close False

        MyFile = Dir

    Loop
End Sub