我需要使用Excel VBA搜索一系列单元格,返回第一个匹配的行号.只要我在搜索值,使用Match功能就可以轻松完成.但我需要搜索公式,而不是值.
当我搜索"= A4 + 2"时,我需要VBA返回"4"...
你可以直接用它做 match
Application.Match("=A4+2", Range("B1:B5").Formula)
会给你4
编辑
您可能会收到来自的255个字符限制的错误Match
.您还可以使用工作表中的输出.只需将此代码放入模块中:
Public Function MATCHFUNC(str As String, rng As Range, Optional fOnly As Boolean, Optional fAdr As Boolean) As Variant Dim i As Long, runner As Variant If UBound(rng.Value, 1) > 1 And UBound(rng.Value, 2) > 1 And Not fAdr Then MATCHFUNC = 0: Exit Function For Each runner In rng i = i + 1 If Not fOnly Or (runner.Text <> runner.Formula) Then If InStr(1, runner.Formula, str, 1) Then If fAdr Then MATCHFUNC = runner.Address Else MATCHFUNC = i Exit Function End If End If Next MATCHFUNC = 0 End Function
您现在可以像普通的工作表一样使用它.以你的照片为例:
MATCHFUNC([string to search for],[range to look in],[1 to look only in cells containing formulas],[1 to get the address in $A$1 format])
=MATCHFUNC("+2",B3:B5) = 1 - it was found in the first cell =MATCHFUNC("2",B1:B5) = 2 - "2" is also in B2 =MATCHFUNC("2",B1:B5,1) = 3 - B2 will be skipped - formulas only =MATCHFUNC("+2",B3:B5,,1) = "$B$3" - address of the first cell with match =MATCHFUNC("9",B1:B5) = 0 - not found in range =MATCHFUNC("2",A1:B5) = 0 - range needs to be only 1 row or 1 column without fAdr =MATCHFUNC("2",A1:B5,,1) = "$B$2" - check goes A1->B1...->A2->B2...
你可能想要使用fAdr = 1
像这样的特殊情况:
=ROW(INDIRECT(MATCHFUNC("2",B4:B5,,1))) = 4 - absolute row of the first cell with match
假设您不想因任何原因检查B1:B3,但您需要绝对行.
你还可以在VBA本身使用它:iVal = MATCHFUNC("=B", Range("B4:B5"))
还可以简单地改进函数本身以输出数组或在一次运行中检查不同的字符串或做你想做的任何事情(如果没有必要,你也可以跳过2 optinal部件,以保持快速和易于理解):)