仅在vba中返回行号

在Excel VBA是有办法从范围只获得行号。

set range=selection 

在运行micro之前,可以select完成多行连续或者不连续或者只依赖用户的单元。 下面的行可以给我行号,但是像这样它会重复每行的行数,但是我只想从行中select的行数中select行数。

 for each cell in range cell.row next cell 

要么

 for each range in SelectedRange.rows range.row next range 

试试这个代码:

 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列

这将只报告一行:

 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 

例如:

在这里输入图像说明

另一个使用字典的变体:

 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