我一直在寻找并完成这项任务已有好几周,但从未找到解决方案。
我希望你们能给我一个解决方案。
我的情况如下:
我有2本excel工作簿
(1st:Log.xlsx - 总结数据,
第二名:data.xls - 数据源)
2.在log.xlsx中,我有生产日期,产品ID和批次#
3.在data.xls中,我有生产收益率结果(不同id的不同工作表)
仅供参考,工作表编号约为100个工作表
4.我想在相同的日期,产品ID和批次#(与Log.xlsx中匹配)匹配产量结果(data.xls),然后在Log.xlsx中显示产量结果
5. data.xls工作表名称与产品ID不同,但实际产品ID显示在单元格B2中
你能告诉我如何做到这一点吗?
非常感谢您的帮助。
谢谢。
答案 0 :(得分:0)
假设代码在log.xlsx中,并且两个工作簿当前都处于打开状态,这会将第4列到第7列从data.xls复制到log.xlsx
Option Explicit
Public Sub DataSummary()
Dim wbData As Workbook
Dim wsLog As Worksheet
Dim wsDataSet As Worksheet
Dim i, j, k As Integer
Dim prodDate As Date
Dim prodID As String
Dim lotNumber As Integer
Set wbData = Workbooks("Data.xls")
Set wsLog = ThisWorkbook.ActiveSheet
For i = 2 To wsLog.UsedRange.Rows.Count
prodDate = wsLog.Cells(i, 1).Value
prodID = wsLog.Cells(i, 2).Value
lotNumber = wsLog.Cells(i, 3).Value
For Each wsDataSet In wbData.Worksheets
If wsDataSet.Cells(2, 2).Value = prodID Then
For j = 4 To wsDataSet.UsedRange.Rows.Count
If wsDataSet.Cells(j, 1).Value = prodDate And wsDataSet.Cells(j, 3).Value = lotNumber Then
wsLog.Cells(i, 4).Value = wsDataSet.Cells(j, 4).Value
wsLog.Cells(i, 5).Value = wsDataSet.Cells(j, 5).Value
wsLog.Cells(i, 6).Value = wsDataSet.Cells(j, 6).Value
wsLog.Cells(i, 7).Value = wsDataSet.Cells(j, 7).Value
Exit For
End If
Next j
Exit For
End If
Next wsDataSet
Next i
End Sub
Here is link to excel files with code and sample data.
以下是附加检查的代码。它把" 0"当没有匹配的时候。
Option Explicit
Public Sub DataSummary()
Dim wbData As Workbook
Dim wsLog As Worksheet
Dim wsDataSet As Worksheet
Dim i, j, k As Integer
Dim prodDate As Date
Dim prodID As String
Dim lotNumber As Integer
Dim foundIt As Boolean
Dim Message As String
Message = "0"
Set wbData = Workbooks("Data.xls")
Set wsLog = ThisWorkbook.ActiveSheet
For i = 2 To wsLog.UsedRange.Rows.Count
foundIt = False
prodDate = wsLog.Cells(i, 1).Value
prodID = wsLog.Cells(i, 2).Value
lotNumber = wsLog.Cells(i, 3).Value
For Each wsDataSet In wbData.Worksheets
If wsDataSet.Cells(2, 2).Value = prodID Then
For j = 4 To wsDataSet.UsedRange.Rows.Count
If wsDataSet.Cells(j, 1).Value = prodDate And wsDataSet.Cells(j, 3).Value = lotNumber Then
wsLog.Cells(i, 4).Value = wsDataSet.Cells(j, 4).Value
wsLog.Cells(i, 5).Value = wsDataSet.Cells(j, 5).Value
wsLog.Cells(i, 6).Value = wsDataSet.Cells(j, 6).Value
wsLog.Cells(i, 7).Value = wsDataSet.Cells(j, 7).Value
foundIt = True
Exit For
End If
Next j
Exit For
End If
Next wsDataSet
If Not foundIt Then
wsLog.Cells(i, 4).Value = Message
wsLog.Cells(i, 5).Value = Message
wsLog.Cells(i, 6).Value = Message
wsLog.Cells(i, 7).Value = Message
End If
Next i
End Sub
请记住,这只是真正解决方案的粗略方面,您需要添加异常处理,更多检查以查看数据是否正确等等。