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

流过昼夜 提交于 2020-01-23 06:13:31

问题


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?


回答1:


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




回答2:


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.




回答3:


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



回答4:


Yeish, I wouldn't do it like that!

Hypothetically, you have a whole folders worth of word and you don't need the extensions, you just want the names. What you would do is go through the word docs and parse them through this function with the type of extension you want removed 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



回答5:


This one works for me.

Sub ShowFilename()
MsgBox ActiveWindow.Parent
End Sub



回答6:


An easy way would be:

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


来源:https://stackoverflow.com/questions/11564857/how-do-i-get-the-current-filename-of-a-word-document-without-the-extension-or-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!