[英]Finding relative row and column number of a range OR Cell
是否可以在范圍內找到范圍或單元格的相對行數和列數。
示例:在下表中(表名“表2”)
如果我使用Find方法並打印地址,如下所示:
Dim loHeaderRow As Range
Set loHeaderRow = ThisWorkbook.Worksheets("Sheet3").ListObjects("Table2").HeaderRowRange
Dim rFindResult As Range
Set rFindResult = loHeaderRow.Find(What:="MajorVersion", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
MsgBox rFindResult.Address
將打印
$C$3
但是rFindResult范圍與父范圍loHeaderRow的相對位置是:
Row number: 1
Column Number: 2
這可以實現嗎? 特別是通過使用標准對象屬性/方法而不需要很長的代碼集?
當您在標題行中找到文本時,您的行號將始終為1
。 至於Column,你可以使用Debug.Print (rFindResult.Column - loHeaderRow.Column) + 1
例如
Sub Sample()
Dim loHeaderRow As Range, rFindResult As Range
Set loHeaderRow = ThisWorkbook.Worksheets("Sheet3").ListObjects("Table2").HeaderRowRange
Set rFindResult = loHeaderRow.Find(What:="MajorVersion", _
LookIn:=xlValues, _
LookAt:=xlWhole, _
MatchCase:=False, _
SearchFormat:=False)
MsgBox "The Row is 1 and the Column is " & _
(rFindResult.Column - loHeaderRow.Column) + 1
End Sub
這將為您提供1
和2
作為行和列號。
嘗試這個:
Sub test2()
Dim mytable As ListObject
Set mytable = Sheet1.ListObjects("Table2") '~~> adjust the sheet code name to suit
Dim myarr: myarr = mytable.Range
Dim i As Long, j As Long
Dim mysrch As String
mysrch = "MajorVersion"
For i = LBound(myarr, 1) To UBound(myarr, 1)
For j = LBound(myarr, 2) To UBound(myarr, 2)
If myarr(i, j) = mysrch Then
Debug.Print "Relative Row: " & i
Debug.Print "Relative Column: " & j
Exit For
End If
Next
Next
End Sub
但是如果你只需要Sid在評論中指出的那樣,那就走他的路。
順便說一句,這只是邏輯,如果要使用那些行號和列號,可以將其更改為函數 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.