繁体   English   中英

如何在excel vba宏中拆分字符串忽略最后一部分

[英]how to split a string in excel vba macros ignoring last portion

我有一个包含路径值的单元格,如:

C:/Videos/New/VideoName.mp4

我只想从那个单元格中走出路径

所以我试过了

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

这样我每次都可以连接该数组中的字符串

但阵列仍然有完整的路径

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建议的后期绑定中(这样可以避免将库早期绑定到项目中):

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

我认为这是通过完整路径解析父文件夹的最简单,最强大的方法:避免复杂的字符串操作,这可能会让一些“不常见”的情况分开(例如Mac的路径不会被“手动”方法解析)。

您可以使用InStrRev()函数:

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

请阅读Jeeped评论的问题。

我建议使用StrReverseInStr函数而不是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM