如何选择在特定列中具有特定文本的单元格

时间:2021-07-21 05:55:37

标签: excel vba range

我希望更改我的地址代码:

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

对于一个更易于管理的代码,当我添加一些新行时,我不必重写代码。所以我正在寻找一个代码,它会在“C”列中查找特定字符串并将其用作活动列的行。

我不希望对任何文本值进行尺寸标注,因为我有数百条不同的行,我确实需要类似的东西:

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

这个给出了一个语法错误,因为我现在不熟悉这个语法。我用这段代码的意思是查看“B”列并在单元格中找到具有“Lower Film Width”的行。

有人可以分享一下代码吗?

1 个答案:

答案 0 :(得分:0)

获取匹配行 (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