请测试下一个代码:
Sub CopyInMaster()
Dim wb As Workbook,mWb As Workbook,mWbPath As String,shMWb As Worksheet,ws As Worksheet
Dim folderPath As String,fileName As String,arrHead,lastERM As Long,lastrWS As Long,arrCopy,i As Long,j As Long
folderPath = ThisWorkbook.path & "\TestImport\" 'use here the folder path where the workbooks to import data exist
'please,take care of the ending"\"
mWbPath = folderPath & "Master.xlsx" 'use here your Master workbook full name
'check if the master workbook is open. If not,open it
For Each wb In Workbooks
If wb.fullName = mWbPath Then Set mWb = wb: Exit For
Next
If mWb Is Nothing Then
Set mWb = Workbooks.Open(mWbPath)
End If
Set shMWb = mWb.Sheets(1) 'if the sheet to be updated in Master wb is not the first one,please adapt the code using its name
'put master headers in an array:
arrHead = shMWb.Range("A1",shMWb.cells(1,shMWb.Columns.count).End(xlToLeft)).value
'iterate between all workbooks to be used in the necessary folder:
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> ""
If Not fileName = mWb.Name Then 'if the master workbook is not in the same folder,this lines can be eliminated (If - End If)
Set wb = Workbooks.Open(folderPath & fileName)
Set ws = wb.Sheets(1)
'copy each mathing column data:
For i = 1 To UBound(arrHead,2)
For j = 1 To ws.cells(12,ws.Columns.count).End(xlToLeft).Column
If arrHead(1,i) = ws.cells(12,j).value Then
lastrWS = ws.cells(ws.rows.count,j).End(xlUp).row 'last row
lastERM = shMWb.cells(shMWb.rows.count,i).End(xlUp).row + 1 'first empty row
arrCopy = ws.Range(ws.cells(13,j),ws.cells(lastrWS,j)).value 'put the range to be copied in an array (to be faster)
shMWb.cells(lastERM,i).Resize(UBound(arrCopy),UBound(arrCopy,2)).value = arrCopy 'drop the array content
End If
Next
Next i
wb.Close False 'close the workbook without saving it
End If
fileName = Dir()
Loop
End Sub
请注意正确调整必要的路径和“主”工作簿全名!
很高兴知道,除了上面的代码,我们这里不提供免费的编码服务。我们(通常)只帮助人们理解他们的编码问题并学习。所以,你应该向我们展示你自己尝试过的东西,并更好地解释要做什么。请理解,我破例了!
知道在提出问题时经常检查它并回答澄清问题(如果有)至少是礼貌的也是很好的。
经过测试,我想收到一些反馈。我询问了澄清,我只是假设这是你喜欢做的。如果不是,请根据代码返回的内容准确描述您需要什么。
本文链接:https://www.f2er.com/5287.html