简体   繁体   中英

How to select a cell that has specific text in specific column

I am looking to change my address code from:

ThisWorkbook.Worksheets("Machine Specification").Cells(7, ActiveCell.Column).Value

To one that's easier to manage so I don't have to rewrite the code when I add some new row. So I am looking for a code that would look for a specific string in column "C" and use that as the row of the active column.

I am not looking to dimension any text value as I have hundreds of different lines, I literally need something like:

ThisWorkbook.Sheets("Machine Specification").Range("C:C").Find(What:="Lower Film Width", LookIn:=x1Values)

This one gives a syntax error as I'm not familiar with this syntax at this moment. What I meant by this code is to look through column "B" and find a row that has "Lower Film Width" in the cell.

Could someone share the code for that, please?

Get the Row of a Match ( Application.Match )

Option Explicit

Sub GetMatchingRowOneLiner()
    MsgBox GetMatchingRow(ThisWorkbook.Worksheets("Machine Specification"), _
        "C", "Lower Film Width")
End Sub

Sub GetMatchingRowTEST()
    
    Const wsName As String = "Machine Specification"
    Const ColumnID As Variant = "C"
    Const Criteria As String = "Lower Film Width"
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
       
    Dim sRow As Long
    sRow = GetMatchingRow(ws, ColumnID, Criteria)
    
    If sRow = 0 Then
        MsgBox "Not found."
    Else
        MsgBox "The row is " & sRow & "."
    End If
    
End Sub

Function GetMatchingRow( _
    ByVal ws As Worksheet, _
    ByVal ColumnID As Variant, _
    ByVal Criteria As String) _
As Long
    Dim rIndex As Variant
    rIndex = Application.Match(Criteria, ws.Columns(ColumnID), 0)
    If IsNumeric(rIndex) Then
        GetMatchingRow = rIndex
    End If
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM