我有很多销售订单,我要填写来自不同excel工作簿和工作表的大量数据。所以我需要一个可以为我做的宏。我有4个不同的Excel工作簿。 1必须插入数据,3我必须从中获取数据。所有Excel工作簿都列出了销售订单,
因此,宏必须扫描每个工作簿中的每个销售订单,然后从工作簿中获取特定数据。
这是我粘贴数据的工作簿示例。
以下是我必须复制数据的工作簿示例。
所以必须复制:
然后将其粘贴到我必须粘贴数据的工作簿中。
如果有人可以给我一个开始的地方或一些代码,我会非常高兴!
答案 0 :(得分:1)
以下编辑的解决方案。不是最漂亮的代码,可能是更好的方法,但它应该以迂回的方式做你想要的。
将此宏复制到您正在复制 TO 的主图书中的模块中,并将其另存为XLSM文件。
将您要复制 FROM 的所有3张(或任意多张)放在某处的其他文件夹中,然后将该文件位置插入在宏观中。
这应循环遍历指定位置的每个文件,抓取除标题行之外的所有已用单元格,并将它们粘贴到主书上Sheet2中的下一个可用行中。
然后宏将针对销售订单号对复制的数据运行vlookup,并粘贴特殊值以将其转回值。最后,它将为下次运行时准备好Sheet2。
显然,如果您的工作表被命名为其他东西,您可以修改或按编号引用它们,但它应该至少为您提供一个起点。
Sub CopyTheData()
Dim Folder As String
Dim File As Variant
Dim wbk As Workbook
Dim This As Worksheet, That As Worksheet
Folder = "[FOLDER LOCATION HERE]"
File = Dir(Folder & "*.*")
Set This = ThisWorkbook.Sheets(1)
Set That = ThisWorkbook.Sheets(2)
Application.ScreenUpdating = False
While (File <> "")
Set wbk = Workbooks.Open(Folder & File)
With wbk
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
Selection.Copy Destination:=That.Range("B65536").End(xlUp)(2).Offset(0, -1)
End With
wbk.Close
File = Dir
Wend
This.Activate
This.Range("B2", Range("A2").End(xlDown).Offset(0, 1)).Formula = "=VLOOKUP(A2, Sheet2!$A:$H,2,FALSE)"
This.Range("C2", Range("A2").End(xlDown).Offset(0, 2)).Formula = "=VLOOKUP(A2,Sheet2!$A:$H,4,FALSE)"
This.Range("D2", Range("A2").End(xlDown).Offset(0, 3)).Formula = "=VLOOKUP(A2,Sheet2!$A:$H,6,FALSE)"
This.Range("E2", Range("A2").End(xlDown).Offset(0, 4)).Formula = "=VLOOKUP(A2,Sheet2!$A:$H,8,FALSE)"
With This.Range("B2", Range("A2").End(xlDown).Offset(0, 4))
.Copy
.PasteSpecial Paste:=xlPasteValues
End With
Columns("D:E").NumberFormat = "m/d/yyyy"
That.Cells.ClearContents
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:1)
Harley的代码看起来不错,如果您只想要使用某些工作表,尽管您可以将以下内容粘贴到要添加到主工作表的每个工作表中。
Dim owb As Workbook
Dim Master As Worksheet
Dim Slave As Worksheet 'the following declares both master and slave as worksheets
fpath = "location of master workbook"
Set owb = Application.Workbooks.Open(fpath) 'opens the file path
Set Master = ThisWorkbook.Worksheets("name of sheet in workbook your pasting from") 'declares this workbook and sheet as "master"
Set Slave = owb.Worksheets("name of sheet in master you are pasting to") 'declares the workbook and sheet you're copying to as "slave"
For j = 1 To 10000 '(the master sheet) 'goes through each row from 1 to 10000
For i = 1 To 10000 '(the slave sheet) 'again does the same and the slave sheet
If Trim(Master.Cells(j, 4).Value2) = vbNullString Then Exit For 'if the ID is blank it will exit and move on to the next row
If Master.Cells(j, 1).Value = Slave.Cells(i, 1).Value Then 'the 1 represents column A, if cell in column A matches the cell in column D in the masterwork book then it will..
Slave.Cells(i, 2).Value = Master.Cells(j, 2).Value
'the cell here represent column B as it's a 2, you can change and add as many as you like to bring through the column
End If
Next
Next
MsgBox ("Successful")