我想找到第n次出现值的单元格地址。
示例:我想知道列中第3个X的单元格地址。
| Andy | X |
| Tony | Y |
| Luke | X |
| Anne | X |
,结果应为B4。
感谢您的帮助。
答案 0 :(得分:0)
试试这段代码:
Sub FindAddress()
Dim stringToFind As String: stringToFind = "X"
Dim timesOfOccurence As Long: timesOfOccurence = 3 'we want third occurence
Dim columnToSearch As Long: columnToSearch = 2 'we search second column - B column
Dim counter As Long: counter = 0
Dim i As Long, occurences As Long
For i = 1 To Cells(Rows.Count, columnToSearch).End(xlUp).Row
If Cells(i, columnToSearch) = stringToFind Then
occurences = occurences + 1
End If
If occurences = timesOfOccurence Then
Exit For
End If
Next
If occurences = timesOfOccurence Then
MsgBox ("Column: " & columnToSearch & " || Row: " & i)
Else
MsgBox ("Specified string didn't occur that many times")
End If
End Sub
答案 1 :(得分:0)
使用Find和FindNext方法如何:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
icounter = 0
Set valuefound = ws.Columns("B:B").Find(What:="X")
'above look for value X in column B
If Not valuefound Is Nothing Then 'if found then
foundaddress = valuefound.Address 'save the address of the first instance found
icounter = icounter + 1 'increment counter
Do
Set valuefound = ws.Columns("B:B").FindNext(valuefound) 'find next value
icounter = icounter + 1 'increment counter
If icounter = 3 Then MsgBox valuefound.Offset(0, -1).Value 'if third instance found then prompt name of person
Loop While Not valuefound Is Nothing And valuefound.Address <> foundaddress
End If
End Sub