Excel VBA:正则表达式 - 获取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12354592/
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
Excel VBA: Regular Expression - get file name
提问by xeo gegry
How do I get just filename (without path and extension)
like "MyFileName"
from the following full path?
C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt
如何
从以下完整路径中
获取像“MyFileName”这样的
文件名(没有路径和扩展名)
?
C:\A_B\CD\E_\F0123456789\G\MyFileName.txt
回答by SeanC
InStrRev
will find the last occurrence of a character in a string. Search for \
and split it there
InStrRev
将查找字符串中最后一次出现的字符。\
在那里搜索并拆分它
FullFileName="C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt"
FileName=mid(FullFileName,instrrev(FullFileName,"\")+1)
now to take off the extension
现在取消扩展
FileNameWithoutExt=left(FileName,instrrev(FileName,".")-1)
回答by shahkalpesh
Public Function GetFileNameWithoutExt(ByVal fullPath As String) As String
Dim fileName As String
Dim fileNameWithoutExt As String
Dim lastSlash As Integer
Dim positionOfDot As Integer
lastSlash = InStrRev(fullPath, "\")
fileName = Mid(fullPath, lastSlash + 1)
positionOfDot = InStr(1, fileName, ".")
fileNameWithoutExt = Mid(fileName, 1, positionOfDot - 1)
GetFileNameWithoutExt = fileNameWithoutExt
End Function
Using the immediate window
使用即时窗口
?GetFileNameWithoutExt("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt")
EDIT: Another method
编辑:另一种方法
Public Function GetFileNameWithoutExt2(ByVal fullPath As String) As String
Dim fileName As String
Dim splittedData
Dim fileNameWithoutExt As String
splittedData = Split(fullPath, "\")
fileName = splittedData(UBound(splittedData))
fileNameWithoutExt = Split(fileName, ".")(0)
GetFileNameWithoutExt2 = fileNameWithoutExt
End Function
回答by Dick Kusleika
If it's a real file that you have access to, you can use Dir
如果它是您有权访问的真实文件,则可以使用 Dir
sFileOnly = Dir(sPathAndFile)
If it's not a real file or you don't have access to it, this will return an empty string.
如果它不是一个真正的文件或者您无权访问它,这将返回一个空字符串。
回答by m4573r
Set regEx = New RegExp
regEx.Pattern = ".*\"
regEx.IgnoreCase = True
filename = regEx.Replace(fullpath, "")
回答by ray
Sub Test()
Dim fileNameOnly As String
fileNameOnly = Left$(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\"))), InStrRev(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\")(UBound(Split("C:\A_B\C.D\E_\F0123456789\G\MyFileName.txt", "\"))), ".") - 1)
Debug.Print Strtf
End Sub