How to get current file name of Word document without extension or full path using macro?

I have a code that retrieves the full path to a file, minus the extension, and I'm trying to change it to save only the file name, 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

The C:\Users\testname of the document is displayed test.docm. How can I change this to display only the file name? Do I need to split the string along \and extract the last part?

+6
source share
6 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

+6
source
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

if, , .

+6

As I did not know how to write code using FSO (isn’t it just for VB, isn’t it?), I wrote this, quite 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
+1
source

Eish, I wouldn’t do that!

Hypothetically, you have a whole folder worth the word, and you do not need extensions, you just need names. What you would do is go through the docs words and parse them through this function with the type of extension you want to remove from the file name

Function removeExtension(myDoc as Document, extension as String)
Dim documentWithoutExtension as String

documentWithoutExtension = replace(myDoc.Name, extension, "")

removeExtension = documentWithoutExtension

End Function
0
source

This one works for me.

Sub ShowFilename()
MsgBox ActiveWindow.Parent
End Sub
0
source

A simple way would be:

Sub Test1() Dim DocName As Document Set DocName = ActiveDocument end sub

Hope this helps!

0
source

All Articles