Dir () Function not returning filename from file path.

kelly mort

Well-known Member
Joined
Apr 10, 2017
Messages
2,169
Office Version
  1. 2016
Platform
  1. Windows
Code:
Sub SaveFileCode
ChDrive ThisWorkbook.Path 
ChDir ThisWorkbook.Path 

DefName = "My File" & Year(Date)

FileSaveAs = Application.GetSaveAsFilename(InitialFileName:=DefName, FileFilter:="Exel Files (*.xlsm),*.xlsm",Title:="Add Name")

If FileSaveAs = False Then 
        MsgBox "Operation terminated"
Else
       Application.EnableEvents=False 
       ThisWorkbook.SaveAs FileName:=FileSaveAs, FileFormat:=52, Password:="", writerespassword:="", ReadOnlyRecommended:=False 
       Application.EnableEvents=True
End Sub

I am using this code to save a copy of my workbook.

What I want to do next is to be able to get the filename ONLY displayed in a message box.

I was using the Dir(FileSaveAs) which kept returning blank until I noticed that the Dir function only works fine if the file is available. And in my case, the file will not exist.

I also tried
Code:
Right (FileSaveAs, InstrRev(FileSaveAs, "\")-1)

It was not able to get me only the filename.


Can someone show me the best way to get to the filename only?
 

Excel Facts

Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
You didn't show an example of the result you are looking for.

Are you expecting the filename with extention? ex. 'My File 2021.xlsm'
 
Upvote 0
No I don't want the extension.

I only need "My File 2021"
 
Upvote 0
How about:

VBA Code:
FileNameWithoutExtensionFromFullPath = Mid(FileSaveAs, InStrRev(FileSaveAs, "\") + 1, InStrRev(FileSaveAs, ".") - InStrRev(FileSaveAs, "\") - 1)
 
Last edited:
Upvote 0
Solution

Forum statistics

Threads
1,214,919
Messages
6,122,260
Members
449,075
Latest member
staticfluids

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top