无法分割多个特殊字符

我试图在单元格A1中的string'C:\ Users \ punateng \ Desktop \ Pending Spec Updates.xlsx'中将单元格值拆分为最后一个“\”,以使单元格B1的结果应该为'C:\ Users \ punateng \桌面\'

我写了下面的代码:

Sub mu() Cells(1, 2).Value = Split(Cells(1, 1).Value, "\") End Sub 

但是我得到的结果是C:在B1单元格。

请帮忙。

这是一个function比一个子更好的情况。

Excel具有查找和searchfunction,但没有FindLastfunction。

在用户定义函数(UDF)中,可以使用Application.WorksheetFunction集合中不可用的一些函数。 其中之一就是InstrRev ,它从string的末尾向后读取string的第一个实例的位置,如“\”。 使用这个小gem的知识和文本编辑function,你可以build立这个UDF:

 Function FileNameFromPath(Path1 As String) 'Test if you have been parsed an network file path If InStr(1, Path1, "\") > 0 Then 'Get whatever is after the last "\" FileNameFromPath = Right(Path1, Len(Path1) - InStrRev(Path1, "\")) Else 'Could be a SharePoint file with http// address If InStr(1, Path1, "\") > 0 Then 'Get whatever is after the last "/" FileNameFromPath = Right(Path1, Len(Path1) - InStrRev(Path1, "/")) Else 'There isn't a path separator there FileNameFromPath = "That ain't a path" End If End If End Function 

所以你可以在工作簿的任何单元格中调用这个UDF,方法是input“= fi”,按Tab键将其粘贴到单元格中,然后select要testing的单元格,并input一个“”括号“)”。

Split返回一个string数组,在这种情况下,它将包含之前用\分隔的input文本的每一部分,所以,实际上你正在返回数组{"C:";"Users";"punateng";"Desktop";"Pending Spec Updates.xlsx"} 。 当您尝试将其粘贴到Cells(1,2) ,VBA只是将其解释为string数组的第一个元素。

相反,你可能想尝试

Cells(1,2).Value=Left(Cells(1,1).Value,InstrRev(Cells(1,1).Value,"\")-1)

它应该find\的最后一个实例,并返回它之前的文本。