如何从文件名 (VBA) 中删除文件扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32024220/
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
How to remove file extension from file name (VBA)
提问by F1990
I have a filename variable that contains : "Filename.csv". To extract the filename from a path I use: Filename=Dir([fStr])where fStris retrieved from the file that I selected.
我有一个包含 : 的文件名变量"Filename.csv"。从我使用的路径中提取文件名:Filename=Dir([fStr])where fStris 从我选择的文件中检索。
I only need the filename without ".csv". How do I remove the ".csv"extension?
我只需要没有".csv". 如何删除".csv"扩展名?
回答by Bond
It's best to use a function like GetBaseName()instead of relying on functions to replace text. Windows allows periods to appear within the base filename so something like this is legitimate:
最好使用类似的函数GetBaseName()而不是依赖函数来替换文本。Windows 允许在基本文件名中出现句点,因此类似这样的内容是合法的:
My .csv for Bob.csv
Using Replace()would result in:
使用Replace()会导致:
My for Bob
Not what you're looking for. A better approach would be:
不是你要找的。更好的方法是:
Filename = CreateObject("Scripting.FileSystemObject").GetBaseName(fStr)
回答by Philippe Grondier
You can use the replace function:
您可以使用替换功能:
Filename = replace(Dir([fStr]),".csv","")
回答by ExcelIsFun_Sometimes
My code runs on various systems which may not allow scripting. I rewrote this to get around this limitation.
我的代码运行在可能不允许编写脚本的各种系统上。我重写了这个来解决这个限制。
Function FileGetBaseNameNoExt(aFilenameStr As String) As String
Dim TmpCnt As Integer
Dim TmpStr As String
FileGetBaseNameNoExt = aFilenameStr
If InStr(aFilenameStr, ".") = False Then
Exit Function
End If
TmpCnt = 1
TmpStr = Left(Right(aFilenameStr, TmpCnt), 1)
While TmpStr <> "."
TmpCnt = TmpCnt + 1
TmpStr = Left(Right(aFilenameStr, TmpCnt), 1)
Wend
'Make Sure the Filename is Not Something Odd like .csv
If TmpCnt < Len(aFilenameStr) Then
FileGetBaseNameNoExt = Left(aFilenameStr, Len(aFilenameStr) - TmpCnt)
End If
End Function

