获取有关指定范围的单元格的行号

时间:2019-02-13 04:06:41

标签: excel vba

我正在尝试获取用vba指定的范围内的单元格的行号。我想获取该范围内单元格的行号,但是我得到的是工作表中单元格的行号。

这是我当前正在使用的vba代码。我设置了一个范围,并在该范围内搜索包含文本字符串“ C”的单元格。找到单元格后,我想更改范围第二列中的值。

Sub trial2()

Dim ActiveWB As Workbook
Dim ActiveWS As Worksheet
Dim rng As Range, findCell As Range

Set ActiveWB = ActiveWorkbook
Set ActiveWS = ActiveWB.ActiveSheet

Set rng = ActiveWS.Range("B4", "C10")

With rng
    Set findCell = .Cells.Find(what:="C")
End With

rng.Cells(findCell.Row, 2).Value = "change to something."

End Sub

运行代码之前:

enter image description here

运行代码后:

enter image description here

包含“ C”的单元格值在工作表的第6行中,但在范围的第3行中。我想知道如何获得范围的第三行。我知道我可以将单元格偏移1列来解决此问题,但是我很好奇要获取相对于定义范围的单元格的行数。

2 个答案:

答案 0 :(得分:2)

一个选择是使用简单的数学运算基于rng第一行的数目进行调整。

rng.Cells(findCell.Row - rng.Row + 1, 2).Value = "change to something."

在这种情况下,6 - 4 + 1 = 3

答案 1 :(得分:1)

您可以使用:

Option Explicit

Sub test()

    Dim rng As Range

    With ThisWorkbook.Worksheets("Sheet1")

        'If your searching area for A,B,C etc is from B4 to B10 just use
        Set rng = .Range("B4:B10").Cells.Find(what:="C")
        'If your searching area for A,B,C etc is from B4 to C10 just use
        Set rng = .Range("B4:C10").Cells.Find(what:="C")

        If Not rng Is Nothing Then
            'Way 1
            .Cells(rng.Row, rng.Column + 1).Value = "change to something."
            'Way 2
            rng.Offset(0, 1).Value = "change to something."
        Else
            MsgBox "No ""C"" found."
        End If

    End With

End Sub