1

If I want to find the row number of a cell in column A with the text containing the string "Total Labor", how can I do that?

Another is how can I find the position of the cell containing that text if it can be in any column and row?

This is what I have, but it returns as an Empty. TotalLaborPos is defined as a Variant.

lastrow = Range("A11").End(xlDown)
TotalLaborPos.Value = ActiveSheet.Match("Total Labor", Range("A11:A" & lastrow), 0)

BigBen
  • 46,229
  • 7
  • 24
  • 40
cd18___
  • 31
  • 4

2 Answers2

1

It's Application.Match not ActiveSheet.Match

If it can be in any column/row then use Find()

E.g.

Dim f As Range
Set f = ActiveSheet.Cells.Find("Total Labor",lookat:=xlWhole,lookin:=xlValues)
If not f is nothing then
   debug.print "found", f.address
end if
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
0

The Worksheet Row of the First Match in a Column

Option Explicit

Sub GetFirstMatchInColumnRowTEST()
    
    Const First As String = "A11"
    Const StringToMatch As String = "Total Labor"
    
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim fCell As Range: Set fCell = ws.Range(First)
    
    Dim mRow As Long: mRow = GetFirstMatchInColumnRow(fCell, StringToMatch)
    If mRow = 0 Then Exit Sub ' not found
    
    ' Continue with code...
    Debug.Print ws.Cells(mRow, fCell.Column).Address(0, 0)
    
End Sub

Function GetFirstMatchInColumnRow( _
    ByVal rg As Range, _
    ByVal StringToMatch As String) _
As Long
    
    If rg Is Nothing Then Exit Function ' no range
    
    ' Create a reference to the Search (Column) Range ('srg').
    Dim wsrCount As Long: wsrCount = rg.Worksheet.Rows.Count
    Dim fRow As Long: fRow = rg.Row
    Dim srCount As Long: srCount = wsrCount - fRow + 1
    Dim srg As Range: Set srg = rg.Cells(1).Resize(srCount)
    
    ' 1.) Using 'Range.Find'.
    Dim mCell As Range: Set mCell = srg.Find(StringToMatch, _
        srg.Cells(srg.Cells.Count), xlFormulas, xlWhole)
    If mCell Is Nothing Then Exit Function ' not found
    
    GetFirstMatchInColumnRow = mCell.Row
    
'    ' 2.) Using 'Application.Match'                                                                                                                                                                                                                                                                                                                                                                                                                                                 '
'    Dim rIndex As Variant: rIndex = Application.Match(StringToMatch, srg, 0)
'    If IsError(rIndex) Then Exit Function ' not found
'
'    GetFirstMatchInColumnRow = srg.Cells(rIndex).Row
    
End Function
VBasic2008
  • 44,888
  • 5
  • 17
  • 28