2012年7月30日 星期一

取得某值最初或最後出現的位置

    在一個資料範圍中,欲取得某一個值最後出現的位置,可以使用以下的程式碼
Sub 取得範圍中最早或最後出現的數值位置()
    With Range("A1:A6")
         Set c = .Find(what:="劉德華", LookIn:=xlValues, lookat:=xlWhole, searchdirection:=xlPrevious)
         If Not c Is Nothing Then MsgBox c.Row
    End With
End Sub
執行該程式可以尋找A1:A6中最後出現劉德華的列號

    如果要尋找最初出現的位置,則改為
Sub 取得範圍中最早或最後出現的數值位置()
    With Range("A1:A6")
         Set c = .Find(what:="劉德華", after:=.Cells(.Cells.Count), LookIn:=xlValues, lookat:=xlWhole, searchdirection:=xlNext)
         If Not c Is Nothing Then MsgBox c.Row
    End With
End Sub

沒有留言:

張貼留言