是否有一种有效的方法来识别字符串中使用基函数的最后一个字符/字符串匹配?也就是说,不是字符串的最后一个字符/字符串,而是字符/字符串在字符串中最后出现的位置。搜索和查找都从左到右工作,所以我不知道如何应用没有冗长的递归算法。现在看来,这种解决方案已经过时了。


当前回答

如何创建一个自定义函数并在您的公式中使用它?VBA有一个内置的函数,InStrRev,它所做的正是您正在寻找的。

把这个放到一个新模块中:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

你的函数看起来像这样(假设原始字符串在B1中):

=LEFT(B1,RSearch(B1,"\"))

其他回答

刚想出这个解决方案,不需要VBA;

找到我的例子中最后出现的“_”;

=IFERROR(FIND(CHAR(1);SUBSTITUTE(A1;"_";CHAR(1);LEN(A1)-LEN(SUBSTITUTE(A1;"_";"")));0)

由内而外解释;

SUBSTITUTE(A1;"_";"") => replace "_" by spaces
LEN( *above* ) => count the chars
LEN(A1)- *above*  => indicates amount of chars replaced (= occurrences of "_")
SUBSTITUTE(A1;"_";CHAR(1); *above* ) => replace the Nth occurence of "_" by CHAR(1) (Nth = amount of chars replaced = the last one)
FIND(CHAR(1); *above* ) => Find the CHAR(1), being the last (replaced) occurance of "_" in our case
IFERROR( *above* ;"0") => in case no chars were found, return "0"

希望这对你有帮助。

在VBA中一个简单的方法是:

YourText = "c:\excel\text.txt"
xString = Mid(YourText, 2 + Len(YourText) - InStr(StrReverse(YourText), "\" ))

如何创建一个自定义函数并在您的公式中使用它?VBA有一个内置的函数,InStrRev,它所做的正是您正在寻找的。

把这个放到一个新模块中:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

你的函数看起来像这样(假设原始字符串在B1中):

=LEFT(B1,RSearch(B1,"\"))

您可以使用我创建的这个函数来查找字符串中的字符串的最后一个实例。

当然,公认的Excel公式是可行的,但它太难以阅读和使用。在某种程度上,你必须把它分解成更小的块,这样它才可维护。下面的函数是可读的,但这无关紧要,因为您在使用命名参数的公式中调用它。这使得使用它很简单。

Public Function FindLastCharOccurence(fromText As String, searchChar As String) As Integer
Dim lastOccur As Integer
lastOccur = -1
Dim i As Integer
i = 0
For i = Len(fromText) To 1 Step -1
    If Mid(fromText, i, 1) = searchChar Then
        lastOccur = i
        Exit For
    End If
Next i

FindLastCharOccurence = lastOccur
End Function

我是这样使用的:

=RIGHT(A2, LEN(A2) - FindLastCharOccurence(A2, "\"))

如果您只查找字符“~”的最后一个实例的位置,那么 = len(替代(字符串 ,"~",""))+ 1

我确信有一个版本将与字符串的最后一个实例一起工作,但我必须回去工作。