如何检查数组中先前位置的重复值?

时间:2019-06-13 21:27:53

标签: excel vba

我正在尝试检查数组中的前一个值,以查看是否重复,如果结束,请结束该函数并保留下一个非重复值。 说你有

lRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    ReDim weeks(1 To lRow - 1)

    For i = 2 To lRow
        weeks(i - 1) = WorksheetFunction.WeekNum(Sheet1.Cells(i, "C"), vbMonday)
        'MsgBox lRow
    Next i

因此向量“周”具有(15,4,8,15,15,4,16)

lRow = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To sizeOf(weeks) 
    addHours= 0
    For j = 2 To lRow
        If WorksheetFunction.WeekNum(Worksheets("Sheet2").Cells(j, "B"), vbMonday) = weeks(i) Then
            addHours= addHours+ Worksheets("Sheet2").Cells(j, "C").Value
            Sheet1.Cells(i + 1, "F") = addHours

        End If
    Next j
    addHours= 0
Next i
WeekHours = addHours

当上面的代码达到“ weeks(3)”时,应跳过该代码,并检查是否重复下一个,并继续跳过,否则请添加。

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

构建字典而不是数组。词典中没有重复的键。

Dim weeks as object, k as variant

lRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
set weeks = createobject("scripting.dictionary")

For i = 2 To lRow
    weeks.Item(WorksheetFunction.WeekNum(Sheet1.Cells(i, "C"), vbMonday)) = vbnullstring
Next i

for each k in weeks.keys
    debug.print k
next k