找到包含部分文本值的行,返回行号

时间:2015-05-12 01:56:58

标签: excel vba

我正在尝试编写一个简单的VBA函数,该函数将返回包含文本值的单独工作表上的范围中的第一行,但可能不是1匹配的精确值。例如:'Farm'位于'Farm123'

我的尝试是:

Public Function Locit(whatcell As Range) As Range
  Set Locit = Sheets(Sheet4).Columns("C").Find(what:="*" & whatcell.Value & "*", lookat:=xlPart)
End Function

毋庸置疑,它失败了,自从我尝试过这种类型的代码已经有好几年了。有人能让我走上正轨吗?

2 个答案:

答案 0 :(得分:0)

这里是您更新的变体

Public Function Locit(whatcell As Range)
    Locit = Sheets("Sheet4").[C:C].Find(whatcell.Value).Row
End Function

但是这个变种更好,我想:

Public Function Locit(whatcell As Range, whatrange As Range)
    Locit = whatrange.Find(whatcell.Value).Row
End Function

输出

enter image description here

答案 1 :(得分:0)

您正在传递查找值,但可以通过传入搜索范围以及要返回的属性来轻松提供其他功能。

Public Function Locit(whatCell As Range, whatColumn As Range, Optional iTYP As Long = 1)
    With whatColumn
        Select Case iTYP
            Case 1   'return row number
                If CBool(Len(whatCell.Value)) Then _
                    If Application.CountIf(.Cells, Chr(42) & whatCell.Value & Chr(42)) Then _
                        Locit = Application.Match(Chr(42) & whatCell.Value & Chr(42), .Cells, 0)
            Case 2   'return cell as range
                If CBool(Len(whatCell.Value)) Then _
                    If Application.CountIf(.Cells, Chr(42) & whatCell.Value & Chr(42)) Then _
                        Set Locit = Application.Index(.Cells, Application.Match(Chr(42) & whatCell.Value & Chr(42), .Cells, 0))
            Case 3   'return cell as address
                If CBool(Len(whatCell.Value)) Then _
                    If Application.CountIf(.Cells, Chr(42) & whatCell.Value & Chr(42)) Then _
                        Locit = Application.Index(.Cells, Application.Match(Chr(42) & whatCell.Value & Chr(42), .Cells, 0)).Address(0, 0)
            Case 4   'return value
                If CBool(Len(whatCell.Value)) Then _
                    If Application.CountIf(.Cells, Chr(42) & whatCell.Value & Chr(42)) Then _
                        Locit = .Cells(Application.Match(Chr(42) & whatCell.Value & Chr(42), .Cells, 0)).Value
        End Select
    End With
End Function

一系列细胞就足够了;您不需要传递工作表,除非您将其作为范围的一部分。例如,使用A1中的 farm ,然后:

=Locit(A1, Sheet4!C:C)

默认情况下,这实际上会返回您正在寻找的行。如果 Farm123 在Sheet4的C4中,那么它将返回4.使用可选的 iTYP 参数可以获得更多信息。

=Locit(A1, Sheet4!C:C, 1)           ◄ returns row number (default)
=Locit(A1, Sheet4!C:C, 2)           ◄ returns C4 as a cell range (probably displays "Farm123" just as if you used =Sheet4!C4)
=Locit(A1, Sheet4!C:C, 3)           ◄ returns "C4" as a string
=Locit(A1, Sheet4!C:C, 4)           ◄ returns "Farm123" as a string

我对INDEX function和/或MATCH function不合适的原因有点不清楚。

相关问题