我已经找了好几个星期了,一直在做这个任务,但一直没有找到解决办法。我希望你们能给我一个解决办法。
我的情况如下:
你能告诉我怎样才能做到这一点吗?
真的很感谢你的帮助。
谢谢。
发布于 2014-03-31 05:36:07
假设代码在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下面链接到带有代码和示例数据的excel文件。
下面是带有附加检查的代码。当没有匹配的时候,它会放"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请记住,这只是粗略的实际解决方案,您需要添加异常处理,更多的检查,看看数据是否正确,等等。
https://stackoverflow.com/questions/22752716
复制相似问题