首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Excel 2010+ VBA -如何搜索范围的公式而不是值

Excel 2010+ VBA -如何搜索范围的公式而不是值
EN

Stack Overflow用户
提问于 2015-12-10 14:11:47
回答 2查看 626关注 0票数 2

我需要使用Excel搜索一系列单元格,返回第一个匹配的行号。只要我在搜索值,匹配函数就很容易做到这一点。但我需要搜索公式,而不是数值。

当我搜索“=A4+2”时,我需要VBA返回"4“。

EN

Stack Overflow用户

回答已采纳

发布于 2015-12-10 14:16:24

你可以直接用match来做

代码语言:javascript
复制
Application.Match("=A4+2", Range("B1:B5").Formula)

会给你4个

编辑

您可能会得到来自Match的255个字符限制的错误。此外,您可能希望使用工作表中的输出。只需将此代码放在模块中:

代码语言:javascript
复制
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])

代码语言:javascript
复制
=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,如:

代码语言:javascript
复制
=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"))

此外,函数本身也可以很容易地进行改进,也可以在一次运行中输出数组或检查不同的字符串,或者做任何您想做的事情(如果没有必要,也可以跳过两个视距部分,以保持它的快速性和易懂性) :)

票数 7
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34204060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档