从 VBA 中的完整文件名中提取路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42462625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract the path from a full file-name in VBA
提问by A.S.H
I m new in VBA and below is my code which is not working, can any one of u can help?
我是 VBA 新手,下面是我的代码不起作用,你们中的任何人都可以提供帮助吗?
Dim nPath1() As String
nPath1() = Split(nPath, "\")
'Declare path as integer
Dim path As Integer
'Getting array length
path = UBound(nPath1())
Dim lastname As String
'For Loop
For i = 0 To path-1
lastname += nPath1(i)+"\"
Next i
The above code is not working; my path string is Root\zTrash - No longer needed\NOC\NOCand what I want is Root\zTrash - No longer needed\NOC.
上面的代码不起作用;我的路径字符串是Root\zTrash - 不再需要\NOC\NOC而我想要的是Root\zTrash - 不再需要\NOC。
回答by A.S.H
If you want to remove just the last item from your path, you can do it this way:
如果您只想从路径中删除最后一项,您可以这样做:
Left(nPath, InStrRev(nPath, "\") - 1)
InStrRev
finds the position of the last occurrence of\
Left
truncates the string until that positionThe
-1
is because you want also to remove that last\
InStrRev
找到最后一次出现的位置\
Left
截断字符串直到那个位置这
-1
是因为您还想删除最后一个\
回答by Fadi
Or you can try:
或者你可以试试:
Sub sTest1()
Dim nPath1 As Variant, st As String
st = "Root\zTrash - No longer needed\NOC\NOC"
nPath1 = Split(st, "\")
ReDim Preserve nPath1(UBound(nPath1) - 1)
st = Join(nPath1, "\")
Debug.Print st
End Sub
This is useful if you want to remove more than one item (not just the last one) by changing 1
to 2 or 3 for example:
如果您想通过更改1
为 2 或 3来删除多个项目(不仅仅是最后一个),这将非常有用,例如:
Sub sTest2()
Dim nPath1 As Variant, st As String, n As Long
st = "Root\zTrash - No longer needed\NOC\NOC"
For n = 1 To 3
nPath1 = Split(st, "\")
ReDim Preserve nPath1(UBound(nPath1) - n)
Debug.Print Join(nPath1, "\")
Next
Results:
结果:
Root\zTrash - No longer needed\NOC
Root\zTrash - No longer needed
Root
回答by Vityata
If you are fan of long formulas, this is another option:
如果您喜欢长公式,这是另一种选择:
left(nPath,len(nPath)-len(split(nPath,"\")(ubound(split(nPath,"\")))))
- The idea is that you split by
\
- Then you get the last value in the array (with ubound, but you split twice)
- Then you get the difference between it and the whole length
- Then you pass this difference to the left as a parameter
- 这个想法是你分裂
\
- 然后你得到数组中的最后一个值(使用 ubound,但你拆分了两次)
- 然后你得到它和整个长度之间的差异
- 然后你将这个差异作为参数传递给左边
回答by dmitry
This
这个
For i = 0 To path-1
gives you full nPath1 array. If you want to skip last element (and I'm not sure what you exactly want), you should use path-2
为您提供完整的 nPath1 数组。如果你想跳过最后一个元素(我不确定你到底想要什么),你应该使用 path-2