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

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

我的尝试是:

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

不用说,它已经失败了,而且我已经尝试了这种types的代码已经有好几年了。 有人能让我走上正轨吗?

这里是你的更新版本

 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 

产量

在这里输入图像说明

您正在传递查找值,但可以通过传递范围来search以及返回哪个属性,从而轻松地提供附加function。

 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中的农场那么:

 =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函数和MATCH函数不合适。