-1

所以我有一个看起来像这样的字符串:

999999999999999999999999999999FFFFFFFFFFF9FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF99999^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^C

我正在尝试计算一系列给定连续字符的第一个实例的长度。

例子:

“9”作为给定的字符,它应该计算第一组 9 并返回 30。

“F”作为给定的字符,对于在 30 个“9”之后开始的第一组连续“F”,它应该返回 11。

我在 Excel 中执行此操作,因此公式/VBA 解决方案是理想的。但如有必要,我可以将任何代码转换为 VBA。我觉得这有一个 Reg-Ex 解决方案,但我是 Reg-Ex 的 Jon Snow,我什么都不知道。

提前感谢您的任何见解/建议。

4

4 回答 4

2

这是一个 REGEX 解决方案。请注意,我们必须转义元字符。

Option Explicit
Function LenFirstInstance(findCHAR As String, searchSTRING As String)
    Dim RE As Object, MC As Object
Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = False
    .ignorecase = False
    .Pattern = Left(findCHAR, 1) & "+"
    If .Pattern Like "[\^$.|?*+()[{]*" Then _
        .Pattern = "\" & .Pattern
    If .Test(searchSTRING) = True Then
        Set MC = .Execute(searchSTRING)
        LenFirstInstance = MC(0).Length
    End If
End With

End Function
于 2016-06-22T17:30:23.523 回答
2

我将把它放在这里以供后代使用:

=IF(SUBSTITUTE(MID($A$1,FIND(A2,$A$1),LEN($A$1)),A2,"")="",LEN($A$1)+1,FIND(MID(SUBSTITUTE(MID($A$1,FIND(A2,$A$1),LEN($A$1)),A2,""),1,1),$A$1,FIND(A2,$A$1)))-FIND(A2,$A$1)

这将计算所需输入的第一组:

在此处输入图像描述

于 2016-06-22T17:27:17.510 回答
1

这有帮助吗?我用您的示例数据进行了尝试,它似乎有效。

Function number_Appearances(ByVal myText As String, ByVal myRng As Range)
Dim cel As Range
Dim txtFound As Boolean
Dim celText$

Dim findText$
findText = myText

Set cel = myRng
celText = cel.Text

Dim celLen&
celLen = Len(celText)

txtFound = True

Dim i&, k&
Dim iChar$
For i = 1 To celLen
    iChar = Mid(celText, i, 1)
    If iChar = findText And txtFound = True Then
        k = k + 1
    ElseIf k > 0 And iChar <> findText Then
        txtFound = False
    End If
Next i

Debug.Print "Found " & k & " " & findText & "'s"
number_Appearances = k
End Function

但我在考虑一个公式之前就开始了这个。@ScottCraner 的建议更可取,IMO。

于 2016-06-22T17:11:03.840 回答
0

我摆脱了我的懒惰,写了 VBA 来解决。谢谢斯科特和布鲁斯。是的,它是 29 岁,而不是 30 岁。再次感谢您。

Public Function count_first_instance_of_consecutive_chars(the_char, the_string)
    Dim counter As Integer
    Dim iter As Long
    Dim is_a_match As Boolean

    is_a_match = False

    If the_char <> vbNullString And the_string <> vbNullString Then
        For iter = 1 To Len(the_string)
            If Mid(the_string, iter, 1) = the_char Then
                If is_a_match = True Then
                    counter = counter + 1
                ElseIf is_a_match = False Then
                    is_a_match = True
                    counter = 1
                End If
            Else
                If is_a_match = True Then
                    count_first_instance_of_consecutive_chars = counter
                    Exit For
                End If
            End If
        Next iter
    End If
End Function
于 2016-06-22T17:22:57.720 回答