VBA Excel-需要在主表的单独列中获取文件名。将数据从多个Excel复制到主表

时间:2018-08-23 16:42:28

标签: excel-vba

在这段代码中,我从多个excel复制数据,但是需要z列的master excel中的那些excel文件名。在这里,我能够复制数据,但是在获取文件名时出现错误。任何人都可以帮助我。随附了代码。

Sub PC()

Dim MyFile As String, MyFiles As String, FilePath As String
Dim t as range
Dim erow As Long
'~~>; Put additional variable declaration
Dim wbMaster As Workbook, wbTemp As Workbook
Dim wsMaster As Worksheet, wsTemp As Worksheet

Set extwbk = ThisWorkbook
 Set x = extwbk.worksheets("Data").Range("M2:M1048576")

FilePath = InputBox(“输入文件路径”)     MyFiles = InputBox(“使用文件路径输入文件扩展名”)

MyFile = Dir(MyFiles)

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

'~~> Set your declared variables
Set wbMaster = ThisWorkbook 'if you want to consolidate files in this workbook
Set wsMaster = wbMaster.Sheets("Data") 'replace Sheet1 to suit

Do While Len(MyFile) > 0
    'Debug.Print MyFile
    If MyFile <> "Aug-2017.xlsm" Then

        Set wbTemp = Workbooks.Open(Filename:=FilePath & MyFile, ReadOnly:=True)
        Set wsTemp = wbTemp.Sheets(1) 'I used index, you said there is only 1 sheet
        '~~> Now directly work on your object
        With wsMaster
            erow = .Range("A" & .Rows.Count).End(xlUp).Row 'get the last row

            wsTemp.Range("N4:X104823").Copy

            .Range("A" & erow).Offset(0, 0).PasteSpecial xlPasteValues
            x.Offset.value = Activesheet.Name

.Range(“ M”&erow).offset(0,12).pasteSpecial xlPasteValues

结尾为

        Set wsTemp = Nothing
        Set wbTemp = Nothing
    End If
    '~~> Load the new file
    MyFile = Dir

Loop

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub

0 个答案:

没有答案