【发布时间】:2018-01-06 03:34:36
【问题描述】:
作为我打算的等效简化示例,此工作表包含从 A 到 E 列和多行的 1-9 之间的任意 5 个数字序列:
| A| B| C| D| E|
1 | 1| 5| 6| 8| 9|
2 | 2| 5| 7| 8| 9|
...
50| 1| 3| 4| 6| 7|
然后我想检查每行沿所有行出现了多少任意两个数字的组合,并用结果填充组合数组:
| 1| 2| 3| 4| 5| 6| 7| 8| 9|
1| | | | | | | | | |
2| | | | | | | | | |
3| | | | | | | | | |
4| | | | | | | | | |
5| | | | x| | | | | |
6| | | | | | | | | |
7| | | | | | | | | |
8| | | | | | | | | |
9| | | | | | | | | |
上面,“x”表示数字 4 和 5 组合出现的行数。
我通过 VBA 代码轻松实现了我的目标,但想知道如何通过 excel-formula 做到这一点,因为它通常会更快。
以防万一有人想检查已经用于此任务的 VBA 代码:
Sub NPairs()
Dim Rn As Long
Dim Cn As Long
For Nrow = 2 To 10
For Ncol = 2 To 10
If NCol = NRow Then GoTo NextN 'Skip, cause would search the combination of the same numbers.
Rn = Plan2.Cells(NRow, 1).Value2
Cn = Plan2.Cells(1, NCol).Value2
Plan2.Cells(Nrow, Ncol) = NMatch(Rn, Cn)
NextN:
Next
Next
End Sub
Private Function Nmatch(Rnumber As Long, Cnumber As Long) As Long
Lastrow = Plan1.Cells(Plan1.Rows.Count, "A").End(xlUp).Row
M = 0
For R = 2 To Lastrow
For C = 1 To 5
If Plan1.Cells(R, C).Value2 = Rnumber Then
For Cl = 1 To 5
If Plan1.Cells(R, Cl).Value2 = Cnumber Then M = M + 1
Next
End If
Next
Next
Nmatch = M
End Function
这可以通过使用数组或字典来固定,我知道。我想知道的是,是否可以通过 excel-formula 以更简单的方式做同样的事情。
【问题讨论】:
-
函数Nmatch中没有定义变量Lnumber。那应该是Rnumber吗?
-
@JohnRC 是的。你是对的。编辑它。
标签: excel excel-formula vba