[英]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 )以獲得結果。
為了避免任何問題,我將使用FileSystemObject
的GetParentFolderName()
方法,可以通過添加引用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評論的問題。
我建議使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.