0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WordVBAでドキュメント名を取得する

Last updated at Posted at 2024-09-29

ExcelVBAでは、色々なコードが公開されていますが、WordVBAでは参考になるもサイトが少ないので、自身の勉強も兼ねて、いくつかのコードを公開していきたいと思います。

これから紹介するのは、WordVBAでドキュメント(文書)のファイル名を取得するコードです。
※同一内容をnoteにも執筆しています。記事はこちら

WordVBA
Sub sb文書名取得テスト()
    Debug.Print zfDocumentName(ActiveDocument, a_拡張子:=True)      'Macroテスト.docm
    Debug.Print zfDocumentName(ActiveDocument, a_拡張子:=False)     'Macroテスト
End Sub

Public Function zfDocumentName(a_doc As Document, Optional a_拡張子 As Boolean = True) As String
'ドキュメント名を取得するユーザー定義関数
'※引数にTRUEを指定するか何も指定しないと拡張子付きで、引数にFALSEを指定すると拡張子なしでファイル名を返すユーザー定義関数

  Dim doc_name As String
  doc_name = a_doc.Name

  If a_拡張子 = True Then
    zfDocumentName = doc_name
  Else
    zfDocumentName = Left(doc_name, InStrRev(doc_name, ".") - 1)
  End If
 
End Function

基本的には拡張子ありの場合には、「ActiveDocument.Name」で取得すればよいので、上記コードを使用する必要はありません。
しかし、拡張子なしのファイル名を取得したい場合には、上記コードを利用すれば、簡単に取得可能です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?