Vba word имя документа

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:Userstest, 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?

asked Jul 19, 2012 at 16:05

Ricardo Altamirano's user avatar

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.

answered Jul 19, 2012 at 16:15

Daniel's user avatar

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

answered Jan 21, 2014 at 23:02

Mad VBA Coder's user avatar

1

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

egor.zhdan's user avatar

egor.zhdan

4,5156 gold badges42 silver badges53 bronze badges

answered Aug 28, 2015 at 10:00

Ben Segar's user avatar

This one works for me.

Sub ShowFilename()
MsgBox ActiveWindow.Parent
End Sub

answered Oct 4, 2017 at 23:56

Shane Sibbett's user avatar

An easy way would be:

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

Paul Roub's user avatar

Paul Roub

36.3k27 gold badges82 silver badges92 bronze badges

answered Apr 26, 2019 at 16:41

MWCA44's user avatar

Chuvak
Продвинутый пользователь
Продвинутый пользователь
 
Сообщения: 102
Зарегистрирован: 11.03.2003 (Вт) 8:39
Откуда: Russia, Ozёrsk
  • ICQ

Word и имя документа

При создании нового документа из VB, он получает имя Документ1.

Дальше будет Документ2 и т.д.

Как задавать свои имена?


RayShade
Scarmarked
Scarmarked
Аватара пользователя

 
Сообщения: 5511
Зарегистрирован: 02.12.2002 (Пн) 17:11
Откуда: Russia, Saint-Petersburg
  • Сайт
  • ICQ

Сообщение RayShade » 02.06.2003 (Пн) 10:48

Сохранить в файл с нужным именем через SaveAs :)


SUPchik
Обычный пользователь
Обычный пользователь
Аватара пользователя

 
Сообщения: 51
Зарегистрирован: 15.10.2008 (Ср) 21:46
Откуда: Луховицы

Re: Word и имя документа

Сообщение SUPchik » 02.06.2009 (Вт) 15:48

а нельзя-ли без сохранения вновь созданному документу присвоить имя?

Нет ни одной надёжной системы безопасности!!!


alibek
Большой Человек
Большой Человек
 
Сообщения: 14205
Зарегистрирован: 19.04.2002 (Пт) 11:40
Откуда: Russia

Re: Word и имя документа

Сообщение alibek » 02.06.2009 (Вт) 15:49

Чтобы оно было в заголовке окна?
Теоретически можно, но оно не работает.
Так что нельзя.

Lasciate ogni speranza, voi ch’entrate.


dormouse
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 140
Зарегистрирован: 10.01.2007 (Ср) 21:58
Откуда: Волжский
  • ICQ

Re: Word и имя документа

Сообщение dormouse » 04.06.2009 (Чт) 11:59

Документ1 — это не имя документа. Это только лишь заголовок его окна
его можно задать после создания дока:

Код: Выделить всё
ActiveWindow.Caption = "Документ666"

В любом случае при попытке сохранить файл, пользователь увидит в диалоге автоподставное имя из первой фразы текста документа или какой-нибудь Doc4.doc, если текста нет

VBA, MSA97



Вернуться в VBA

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1

title ms.prod ms.assetid ms.date

Working with Document Objects

word

af304f65-6cdd-ff7d-a81f-cce0161f2b47

06/08/2017

Working with Document Objects

In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection. This topic includes Visual Basic examples related to the following tasks:

  • Creating a new document

  • Opening a document

  • Saving an existing document

  • Saving a new document

  • Activating a document

  • Determining if a document is open

  • Referring to the active document

Creating a new document

The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a document.

A better way to create a document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following example, the Document object returned by the Add method is assigned to an object variable. Then, several properties and methods of the Document object are set. You can easily control the new document using an object variable.

Sub NewSampleDoc() 
    Dim docNew As Document 
    Set docNew = Documents.Add 
    With docNew 
        .Content.Font.Name = "Tahoma" 
        .SaveAs FileName:="Sample.doc" 
    End With 
End Sub

Opening a document

To open an existing document, use the Open method with the Documents collection. The following instruction opens a document named Sample.doc located in the MyFolder folder.

Sub OpenDocument() 
    Documents.Open FileName:="C:MyFolderSample.doc" 
End Sub

Saving an existing document

To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.

Sub SaveDocument() 
    Documents("Sales.doc").Save 
End Sub

You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.

Sub SaveAllOpenDocuments() 
    Documents.Save 
End Sub

Saving a new document

To save a single document, use the SaveAs2 method with a Document object. The following instruction saves the active document as «Temp.doc» in the current folder.

Sub SaveNewDocument() 
    ActiveDocument.SaveAs FileName:="Temp.doc" 
End Sub

The FileName argument can include only the file name or the complete path (for example, «C:DocumentsTemporary File.doc»).

Closing documents

To close a single document, use the Close method with a Document object. The following instruction closes and saves the document named Sales.doc.

Sub CloseDocument() 
    Documents("Sales.doc").Close SaveChanges:=wdSaveChanges 
End Sub

You can close all open documents by applying the Close method of the Documents collection. The following instruction closes all documents without saving changes.

Sub CloseAllDocuments() 
    Documents.Close SaveChanges:=wdDoNotSaveChanges 
End Sub

The following example prompts the user to save each document before the document is closed.

Sub PromptToSaveAndClose() 
    Dim doc As Document 
    For Each doc In Documents 
        doc.Close SaveChanges:=wdPromptToSaveChanges 
    Next 
End Sub

Activating a document

To change the active document, use the Activate method with a Document object. The following instruction activates the open document named Sales.doc.

Sub ActivateDocument() 
    Documents("Sales.doc").Activate 
End Sub

Determining if a document is open

To determine if a document is open, you can enumerate the Documents collection by using a For Each…Next statement. The following example activates the document named Sample.doc if the document is open, or opens Sample.doc if it is not currently open.

Sub ActivateOrOpenDocument() 
    Dim doc As Document 
    Dim docFound As Boolean 
 
    For Each doc In Documents 
        If InStr(1, doc.Name, "sample.doc", 1) Then 
            doc.Activate 
            docFound = True 
            Exit For 
        Else 
            docFound = False 
        End If 
    Next doc 
 
    If docFound = False Then Documents.Open FileName:="Sample.doc" 
End Sub

Referring to the active document

Instead of referring to a document by name or by index number—for example, Documents("Sales.doc") —the ActiveDocument property returns a Document object that refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.

Sub ActiveDocumentName() 
    If Documents.Count >= 1 Then 
        MsgBox ActiveDocument.Name 
    Else 
        MsgBox "No documents are open" 
    End If 
End Sub

Понравилась статья? Поделить с друзьями:
  • Vba word изменить цвет текста
  • Vba word значения таблицы
  • Vba word знак абзаца
  • Vba word защита документа
  • Vba word заполнение таблиц