简体   繁体   中英

How to remove file extension from file name (VBA)

I have a filename variable that contains : "Filename.csv" . To extract the filename from a path I use: Filename=Dir([fStr]) where fStr is retrieved from the file that I selected.

I only need the filename without ".csv" . How do I remove the ".csv" extension?

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:

My .csv for Bob.csv

Using Replace() would result in:

My  for Bob

Not what you're looking for. A better approach would be:

Filename = CreateObject("Scripting.FileSystemObject").GetBaseName(fStr)

您可以使用替换功能:

Filename = replace(Dir([fStr]),".csv","")

Too late to answer it, might be helpful for future

Try this

Mid(fileName, 1, InStr(1, fileName, ".") - 1)

It will work with any file extension or filename

For example:

fileName : ThisIsMyFile.csv

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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