我是这个宏观世界的新手。从yday开始研究它。 我创建了一个宏。 excel工作簿有两张。 sheet1和sheet2
Sheet 1中:
A B C D E
1 2 3 4 3
5 6 7 8 2
9 10 11 12 1
11 12 14 14 3
Sheet 2中:
A B C D E
1 2 3 4 7
13 14 17 20 2
5 6 7 8 1
因此当sheet2中的行(第1个A,B,C,D)与sheet1中的行匹配时,E中的值应该相乘并存储在另一个工作表中。 例如, sheet2,1 2 3 4与sheet1中的1 2 3 4匹配,因此E(7和3)中的数字应该相乘,结果应存储在sheet3中。
下面是我开发的片段。
Sub test()
Dim sh1 As Range
Set sh1 = Sheet1.UsedRange
Dim sh2 As Range
Set sh2 = Sheet2.UsedRange
Dim sh3 As Range
Set sh3 = Sheet3.UsedRange
For i = 1 To sh1.Rows.Count
For m = 1 To sh2.Rows.Count
Match = True
For j = 1 To sh1.Columns.Count
If (sh1.Cells(i, j).Value <> sh2.Cells(m, j).Value) Then Match = False
If (Match = False) Then Exit For
Next j
If Match = True Then sh1.Cells(i, 4).Value = _
sh1.Cells(i, 4).Value * sh2.Cells(m, 4).Value
Next m
Next i
End Sub
这很好用。但这是一种线性搜索,所以当给出大量数据时,excel会被挂起。 是否有更多最佳解决方案?也许像二进制搜索或排序搜索。
答案 0 :(得分:0)
这对我的测试数据非常快。我对您的工作表引用做了一些假设,并且能够使用一些辅助列。您还可以使用更可靠的方式来获取最后一行,但这至少应该让您关闭:
Sub Test()
Dim lrSheet1 As Long, _
lrSheet2 As Long, _
counter As Long
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
With Sheet2
lrSheet2 = .UsedRange.Rows.Count
.Range("F1:F" & lrSheet2).Formula = "=CONCATENATE(A1,B1,C1,D1)"
End With
With Sheet1
lrSheet1 = .UsedRange.Rows.Count
.Range("F1:F" & lrSheet1).Formula = "=CONCATENATE(A1,B1,C1,D1)"
.Range("G1:G" & lrSheet1).Formula = "=Match(F1,Sheet2!F:F,0)"
End With
With Sheet3
For counter = 1 To lrSheet1
If IsNumeric(Sheet1.Range("G" & counter)) Then _
Sheet3.Range("A" & counter).Value = Sheet1.Range("E" & counter).Value * Sheet2.Range("E" & Sheet1.Range("G" & counter)).Value
Next counter
End With
Sheet1.Range("F1:G" & lrSheet1).Delete
Sheet2.Range("F1:F" & lrSheet2).Delete
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
End Sub
基本上它使用2个公式。第一个将值连接在一起。匹配公式返回Sheet2上匹配的行引用。一旦你有了这个,只需要循环遍历Sheet1上的值,如果有一个数字(意味着匹配),你将Sheet1第5列的值乘以Sheet2第5列的匹配值(行号)。
关于我的方法的限制是如果你在Sheet2上有多个匹配(意味着1234存在多次)。不确定这是否可能。如果是,则需要稍微不同的方法......