从后面的单词计数中获取第一个给定的符号

时间:2016-12-08 20:36:29

标签: vba excel-vba excel

我是VBA的初学者,需要我的学校作业帮助。

Function CountfromBack(tekst As String, sümbol As String) As Integer
    CountfromBack = 0
    lengthie = Len(tekst)
    For i = 1 To lengthie
        s = Mid((tekst), i, 1)
        If s = sümbol Then
            CountfromBack = i
            Exit For
        End If
    Next i
    CountfromBack = (lengthie - CountfromBack + 1)
    End Function

这是该功能目前的功能。对于B9中的文本和符号" e"它给出了答案6,但它应该是1,考虑到我正在寻找从后面读取的第一个给定符号。另外,如果符号不在单元格中,我应该如何返回0?

https://i.gyazo.com/491edb81d87749407569832b2c634802.png

2 个答案:

答案 0 :(得分:1)

从最后一个字母到第一个字母迭代:

Function CountfromBack(tekst As String, sümbol As String) As Integer
    Dim lengthie as Long, i as Long, s as String
    CountfromBack = 0
    lengthie = Len(tekst)
    For i = lengthie To 1 Step -1
        s = Mid((tekst), i, 1)
        If s = sümbol Then
            CountfromBack = lengthie - i + 1
            Exit Function
        End If
    Next i

End Function

enter image description here

答案 1 :(得分:1)

您可以使用VBA功能来完成工作:

Function CountfromBack(tekst As String, sümbol As String) As Integer
    CountfromBack = InStr(StrReverse(tekst), sümbol)
End Function

(但我建议您选择Scott's answer,因为您至少完成了该解决方案的部分工作。)