假設代碼是在log.xlsx,和這兩個工作簿當前打開,這將通過複製7立柱4從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
請記住,這只是真正解決粗糙scetch,你需要添加異常處理,更多的檢查,看看數據是否正確等
非常感謝你!我終於可以總結數據! 正如專家預計的那樣。再次感謝你!。 我可以再問一個問題嗎? 我應該添加什麼,以顯示「0」的批號沒有收益/ 身份不明的批號? 提前謝謝! – Nesloais