根据行中其他单元格的内容在Excel 2007中填充单元格

时间:2013-01-09 17:09:07

标签: excel excel-vba vba

我有一个Excel 2007电子表格,其中填充了四列(V1 V2,V3 V4),其中包含以逗号分隔的值(整数[0-20])。价值观不一定是连续的 Excel Spreadsheet: example data and output
我想创建一个新列(例如newV),如果它包含在该行前四列中的至少两列中,则其单元格只包含一个整数。可以使用Excel中的公式或宏来完成吗?如果是这样,那么接近这个的好方法是什么?谢谢。

1 个答案:

答案 0 :(得分:2)

如果每个值只能在每个单元格中出现一次:

Function IfAtLeast(rng As Range, num As Integer)
    Const SEP As String = ","
    Dim c As Range, d As Object, arr, i As Long, tmp, k
    Dim rv As String
    rv = ""
    Set d = CreateObject("scripting.dictionary")
    For Each c In rng
        arr = Split(c.Value, SEP)
        For i = LBound(arr) To UBound(arr)
            tmp = Trim(arr(i))
            If Not d.exists(tmp) Then d.Add tmp, 0
            d(tmp) = d(tmp) + 1
        Next i
    Next c
    For Each k In d.keys
        If d(k) >= num Then rv = rv & IIf(Len(rv) > 0, ",", "") & k
    Next k
    IfAtLeast = rv
End Function

用法:

=IfAtLeast(A2:D2,2)

编辑:如果您在解决UDF问题时遇到问题,那么使用子程序调试问题通常会更容易

Sub Tester()
    debug.print IfAtLeast(Activesheet.Range("A2:D2"), 2)
End Sub