I have code that extracts the full path of a file, minus the extension, and I'm trying to modify it to only store the name of the file, once again without the extension.
Sub ShowFilename()
Dim pathName As String
With ActiveDocument
If Len(.Path) = 0 Then
.Save
End If
If Right(.Name, 1) = "x" Then
pathName = Left$(.FullName, (Len(.FullName) - 5))
Else
pathName = Left$(.FullName, (Len(.FullName) - 4))
End If
End With
MsgBox pathName
End Sub
This displays C:\Users\test
, and the document's name is test.docm
. How can I modify this to only display the filename? Do I need to split the string along \
and extract the last part?
Using field codesGo to Insert > Header or Footer. Select Edit Header or Edit Footer. Select Quick Parts, and select Field. In the Field names list, choose the field you want (such as FileName, Date, Author, or Title), choose the format you want in the Field properties section.
Another way to insert the file name without the extension is to use a different field. For instance, you could use File Properties to save the filename by typing it in manually without the extension. You could then use the DOCPROPERTY field to recall that specific property and insert it in your document.
The default file extension for all Word documents is '. docx'.
FSO has a set of methods for this type of thing, one of which is "getBaseName"
Msgbox CreateObject("scripting.filesystemobject").getbasename(o.Name)
http://msdn.microsoft.com/en-us/library/xhxzwwe1(v=vs.84).aspx
Sub ShowFilename()
Dim pathName As String
Dim o As Document
Set o = ActiveDocument
If InStrRev(o.Name, ".") <> 0 Then
MsgBox Left(o.Name, InStrRev(o.Name, ".") - 1)
Else
MsgBox o.Name
End If
End Sub
I initially posted this without the if, which would error if the file had never been saved, or had no extension.
As I was not able write code using FSO (isn't it only for VB, is it?), I wrote this one, quite self explanatory :)
Dim oldFilename As String
oldFilename = ActiveDocument.Name
If Right(oldFilename, 5) = ".docx" Then
MsgBox ("subtract .docx")
oldFilename = Left(oldFilename, Len(oldFilename) - 5)
ElseIf Right(oldFilename, 4) = ".doc" Then
MsgBox ("subtract .doc")
oldFilename = Left(oldFilename, Len(oldFilename) - 4)
Else
MsgBox ("no extension yet")
End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With