VBA重复的数字相邻
好的,我有一个Excel中的可变大小的数组。 使用VBA我想查找是否有任何重复的值,所以相邻的值是相同的,而不是在整个列。
我知道,只要在excel中,你可以使用if语句,但是你怎样才能使用for循环把它分散到整个表格中。
我非常新手vba。 这是我第一次尝试,虽然没有工作,我不知道如何继续。
总数是由用户input的值
ok = True For j = 2 To 24 For l =1 to total If ActiveCell.Offset(j, l).Select = ActiveCell.Offset(j + 5, l) And ActiveCell.Offset(j + 4, l) And ActiveCell.Offset(j + 3, l) And ActiveCell.Offset(j + 2, l) And ActiveCell.Offset(j + 1, l) Then ok = False End if Next Next
如果您只想标记立即重复的行,只需检查上面一行中的值,看看是否相同。 如果是这样,请标记列。 例如:
With Range("B2:B24") .Formula = "=IF(A2=A1,""X"","""")" .Value = .Value End With
下面的数据集就是这样的:
╔════════╦═══════╗ ║ Col A ║ Col B ║ ╠════════╬═══════╣ ║ 17 ║ ║ ║ 44 ║ ║ ║ 44 ║ X ║ ║ 44 ║ X ║ ║ 15 ║ ║ ║ 93 ║ ║ ║ 93 ║ X ║ ║ 16 ║ ║ ╚════════╩═══════╝
如果你只是想检查列中是否有重复的部分,下面的部分就是你要做的。
Sub arrayDuplicateCheck() Dim arrValues() As Variant Dim lrow As Long, i As Long, ok As Boolean ok = False lrow = Cells(Rows.Count, 1).End(xlUp).Row arrValues = Range(Cells(1, 1), Cells(lrow, 1)) For i = 1 To UBound(arrValues, 1) - 1 If arrValues(i, 1) = arrValues(i + 1, 1) Then ok = True Exit For End If Next i MsgBox (ok) End Sub
当前正在检查列A中的值,如果您想检查另一列,则必须调整分配给该数组的范围。 执行此操作,将arrValues = Range(Cells(1, 1), Cells(lrow, 1))
为要评估的列号。 如果要更改数组列,则需要将lrow
variables更新为相同的列号。
例如, arrValues = Range(Cells(1, 4), Cells(lrow, 4))
现在将从Column D
创build数组。
编辑:如果你想检查下面的所有5行是否匹配,那么你可以把For
和If
语句改成这样:
For i = 1 To UBound(arrValues, 1) - 5 If arrValues(i, 1) = arrValues(i + 1, 1) _ And arrValues(i, 1) = arrValues(i + 2, 1) _ And arrValues(i, 1) = arrValues(i + 3, 1) _ And arrValues(i, 1) = arrValues(i + 4, 1) _ And arrValues(i, 1) = arrValues(i + 5, 1) Then ok = True Exit For End If Next i