例如,我从B3开始有以下数据:
B3 qqq
B4 www
B5 eee
B6 qqq
B7 qqq
B8 rrr
现在,我想遍历整个范围B:B
,并找到并停止在该范围内存在的 LAST qqq
的单元格地址中(在此qqq
在B7
范围内的情况下
注意:qqq
,www
,eee
等值是从用户表单的组合框中选择的。
答案 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