Word VBA/マクロ 備忘録

作業効率化のため作成したマクロをバックアップ代わりにアップしていきます。

【Word VBA/マクロ】フォルダ内の全てのWordファイルにドキュメントプロパティの作成者名を設定

サンプルコードでできること

フォルダ内のWordファイルのドキュメントプロパティの作成者名をセットします。

Sub setDocumentProperty_Author_Folder()
    Dim Path As String, strName As String
    Dim fs As Scripting.FileSystemObject
    Dim baseFolder As Scripting.Folder
    Dim mySubFile As Scripting.File, mySubFiles As Scripting.FILES
    Dim dc As Document, hidFile As Boolean
    Dim dlg As FileDialog
    
    strName = "○○" '作成者名を代入
    
    Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
    
    ' キャンセルボタンクリック時にマクロを終了
    If dlg.Show = False Then Exit Sub
    ' フォルダーのフルパスを変数に格納
    Path = dlg.SelectedItems(1)
    
    Set fs = New Scripting.FileSystemObject
    Set baseFolder = fs.GetFolder(Path)
    Set mySubFiles = baseFolder.FILES
    
    For Each mySubFile In mySubFiles
        hidFile = False
        '隠しファイルの判定
        If mySubFile.Attributes = 2 Or _
            mySubFile.Attributes = 34 Then
            hidFile = True
        End If
        
        If hidFile = False Then
            If fs.GetExtensionName(mySubFile.Path) = "doc" Or _
                fs.GetExtensionName(mySubFile.Path) = "docx" Then
                Documents.Open mySubFile.Path
                Set dc = ActiveDocument
                With dc
                    .BuiltInDocumentProperties("Author") = strName
                    .Close SaveChanges:=True
                End With
            End If
        End If
    Next
End Sub