You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改VBA FindN函数以在单个单元格返回字符所有出现位置?

汇总特定字符所有出现位置的VBA函数

以下是修改后的VBA函数,可直接返回目标字符串中指定字符的所有出现位置,用逗号分隔显示在单个单元格中:

Function FindAllPositions(sFindWhat As String, sInputString As String) As String
    Dim currentPos As Integer
    Dim positions As String
    Application.Volatile
    
    currentPos = 0
    positions = ""
    
    Do
        currentPos = InStr(currentPos + 1, sInputString, sFindWhat)
        If currentPos > 0 Then
            positions = positions & IIf(positions <> "", ", ", "") & CStr(currentPos)
        End If
    Loop While currentPos > 0
    
    FindAllPositions = IIf(positions = "", "未找到匹配", positions)
End Function

使用方法

在Excel单元格中输入公式:

=FindAllPositions("要查找的字符", 目标单元格)

例如,要查找A1单元格中所有逗号的位置,输入:

=FindAllPositions(",", A1)

改动说明

  • 函数返回类型从Integer改为String,用于存储多个位置的拼接结果
  • 改用Do-Loop循环自动遍历所有匹配项,无需指定N值
  • 自动拼接找到的位置,用逗号分隔
  • 增加无匹配时的提示文本,避免返回空值

您好,我使用上述代码可查找语句中特定字符的多次出现位置,但目前需根据公式中的n值在不同单元格返回对应结果。我希望将该字符的所有出现位置汇总显示在同一个单元格中,请告知如何修改代码实现此需求。

内容的提问来源于stack exchange,提问作者jaga jagga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:40:19