如何使用宏查找范围内的LAST(重复)值?

时间:2019-06-28 04:25:38

标签: excel vba

例如,我从B3开始有以下数据:

B3    qqq
B4    www
B5    eee
B6    qqq
B7    qqq
B8    rrr

现在,我想遍历整个范围B:B,并找到并停止在该范围内存在的 LAST qqq的单元格地址中(在此qqqB7范围内的情况下

注意:qqqwwweee等值是从用户表单的组合框中选择的。

3 个答案:

答案 0 :(得分:1)

此代码将为您服务:

Sub rep()

Dim c As Range
Dim add As String
Dim add1 As String

With ActiveSheet.Range("B:B")
    Set c = .Find("qqq", LookIn:=xlValues) ' change qqq with other string or Userform Input variable
    If Not c Is Nothing Then
        add = c.Address
        Do
            add1 = c.Address
            Set c = .FindNext(c)
            If c.Address = add Then GoTo E
        Loop
        End If
End With

E:

MsgBox add1

End Sub

答案 1 :(得分:1)

使用Dictionary尝试以下代码(您需要通过从菜单转到“工具”->“引用”来添加对Microsoft脚本运行时的引用)

Option Explicit
Sub FindLastOccurenceOfRepepetiveValue()
    Dim dict As Dictionary, lastRow As Long, i As Long, val As String
    lastRow = Cells(Rows.Count, 2).End(xlUp).Row
    Set dict = New Dictionary
    For i = 1 To lastRow
        val = Cells(i, 2).Value
        If dict.Exists(val) Then
            dict(val) = dict(val) + 1
        Else
            dict(val) = 1
        End If
    Next

    For i = lastRow To 1 Step -1
        If dict(Cells(i, 2).Value) > 1 Then
            MsgBox "Repetetive value found"
            Cells(i, 2).Select
            Exit For
        End If
    Next
End Sub

答案 2 :(得分:1)

您可以尝试:

Option Explicit

Sub test()

    Dim LastRow As Long, i As Long
    Dim arr As Variant
    Dim rngFound As Range
    Dim SearchValue As String

    'Change this to get the value from the userform
    SearchValue = "qqq"

    With ThisWorkbook.Worksheets("Sheet1")
        'Find the last row of column B
        LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
        'Create an array with all the values
        arr = .Range("B3:B" & LastRow).Value
        'Loop array
        For i = LBound(arr) To UBound(arr)
            'If there is a match
            If arr(i, 1) = SearchValue Then
                Set rngFound = .Range("B" & i + 2)

            End If

        Next i

        If Not rngFound Is Nothing Then
            MsgBox "The last cell value " & SearchValue & " found is :" & rngFound.Address
        Else
            MsgBox "Value not found."
        End If

    End With

End Sub