2016-01-23 85 views
0

在excel中vba有辦法從範圍中獲取行號。返回行號僅在vba中

set range=selection 

選擇可以完成多行連續或非連續或只有它依賴於用戶在運行micro之前的單元格。 下面的行可以給我行數,但是像這樣它會爲每個單元格重複行,但是我只希望從行中選擇的任意數量的單元格只行數一次。

for each cell in range 

    cell.row 

next cell 

for each range in SelectedRange.rows 

    range.row 

next range 

回答

1

試試這個代碼:

Sub test() 
Dim Rng As Range, CL As Range 

Set Rng = Selection 

For Each CL In Application.Intersect(Rng.EntireRow, Rng.Worksheet.Columns(1)) 
    Debug.Print CL.Row 
Next 
End Sub 

注意:您可以使用任何列2,3,4 .....

+0

非常感謝你。我用你的方法。 –

+0

@MehmoodHassan,不客氣。 – Fadi

1

這會報告每行只有一次:

Sub dural() 
    Dim c As Collection 
    Set c = New Collection 
    On Error Resume Next 
     For Each r In Selection 
     c.Add r.Row, CStr(r.Row) 
     Next r 
    On Error GoTo 0 

    msg = "" 

    For i = 1 To c.Count 
     msg = msg & vbCrLf & c.Item(i) 
    Next i 
    MsgBox msg 
End Sub 

例如:

enter image description here

+0

非常感謝。我使用Fadi方法獲取行號,然後將其保存在Collection中。 –

0

另一種變體使用詞典:

Sub dural2() 
    Dim dic As Object: Set dic = CreateObject("Scripting.Dictionary") 
    Dim r As Range 
    dic.comparemode = vbTextCompare 
    For Each r In Selection 
     If Not dic.exists(r.Row) Then dic.Add r.Row, "" 
    Next r 
    MsgBox Join(dic.keys, Chr(10)) 
End Sub