如何在Excel VBAmacros中忽略掉最后一部分的string

我有一个单元格包含path值,如:

C:/Videos/New/VideoName.mp4 

我只想从那个牢房里走出去

所以我试了

 elementArray = Split(Cells(4, 2), "/") 

这样我就可以每次连接数组中的string

但arrays仍然有完整的path

 elementArray[0]=C:/Videos/New/VideoName.mp4 

怎样才能忽略文件名并独自走上路?

您是否正在使用和/或需要正斜杠(例如/Chr(47) )或反斜杠(例如\Chr(92) )似乎存在一些混淆。 尝试这样的事情:

 dim sPath as string, sFullPath as string sFullPath = "C:/Videos/New/VideoName.mp4" ' or C:\Videos\New\VideoName.mp4 if len(sFullPath) > len(replace(sFullPath, Chr(47), vbnullstring)) then sPath = replace(sFullPath, split(sFullPath, Chr(47))(ubound(split(sFullPath, Chr(47)))), vbnullstring) debug.print sPath & " with forward slashes" elseif len(sFullPath) > len(replace(sFullPath, Chr(92), vbnullstring)) then sPath = replace(sFullPath, split(sFullPath, Chr(92))(ubound(split(sFullPath, Chr(92)))), vbnullstring) debug.print sPath & " with back-slashes" else debug.print "unknown separator" end if 

查看VBE的即时窗口( Ctrl + G )获取结果。

为了避免任何问题,我将使用FileSystemObjectGetParentFolderName()方法,通过添加参考Microsoft Scripting Runtime

 Dim fso As New FileSystemObject parentFolder = fso.GetParentFolderName("your path") 

或者在后期绑定中,如@SOofWXLS所build议的(这样可以避免将库早期绑定到项目中):

 Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") parentFolder = fso.GetParentFolderName("your path") 

我认为这是通过完整pathparsing父文件夹的最简单和最稳健的方式:避免复杂的string操作,这可能会让一些“不太常见”的情况分开(例如,Mac的path不会被“手动”方法parsing)。

你可以使用InStrRev()函数:

 With Cells(4, 2) MsgBox Mid(.Value, 1, InStrRev(.Value, "\") - 1) End With 

请阅读Jeeped对这个问题的评论。

我build议使用StrReverse和InStr函数而不是Split

 Dim s As String, f As String s = "C:\Videos\New\VideoName.mp4" f = StrReverse(s) 'FileName 'f = Left(f, InStr(1, f, "\") - 1) 'Path f = Right(f, InStr(1, f, "\")) f = StrReverse(f) MsgBox f 'returns: VideoName.mp4 or path - read above comments