Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current filename of a Word document, without the extension or full path, using a macro?

Tags:

ms-word

vba

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?

like image 893
Ricardo Altamirano Avatar asked Jul 19 '12 16:07

Ricardo Altamirano


People also ask

How do I get the FileName to show in Word?

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.

How do I insert FileName in Word without extension?

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.

What is a latest default file extension for all Word documents?

The default file extension for all Word documents is '. docx'.


3 Answers

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

like image 176
Tim Williams Avatar answered Sep 17 '22 20:09

Tim Williams


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.

like image 43
Daniel Avatar answered Sep 18 '22 20:09

Daniel


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
like image 33
Mad VBA Coder Avatar answered Sep 16 '22 20:09

Mad VBA Coder