仅在vba中返回行号

时间:2016-01-23 17:32:34

标签: excel vba excel-vba

在excel vba中,只能从范围获取行号。

 set range=selection

选择可以在运行micro之前连续完成多行连续或非连续完成或仅依赖于用户的单元格。 以下行可以给我行号,但是像这样它会重复每个单元格的行,但我只想从行中选择的任意数量的单元格中只有一行行号。

for each cell in range

    cell.row

next cell

for each range in SelectedRange.rows

    range.row

next range

3 个答案:

答案 0 :(得分: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 .....

答案 1 :(得分: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

答案 2 :(得分: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