-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する
-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行
※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定
Option Explicit
Private Sub CommandButton1_Click()
'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False
Dim wd As New Word.Application
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim strFolderPath As String
strFolderPath = ThisWorkbook.Path & "\WORK"
'フォルダ選択
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = True Then
strFolderPath = .SelectedItems(1)
End If
End With
Debug.Print "strFolderPath=" & strFolderPath
Dim file As Object
Dim files As Object
Set files = fso.GetFolder(strFolderPath).files
For Each file In files
If file.Name Like "*.docx" Then
Debug.Print "file.Name=" & file.Name
Dim textfile As String
textfile = Replace(file.Name, ".docx", ".txt")
If Dir(strFolderPath & "\" & textfile) <> "" Then
Kill strFolderPath & "\" & textfile
End If
With wd
.Documents.Add
.Documents.Open Filename:=strFolderPath & "\" & file.Name, ReadOnly:=True
.ActiveDocument.SaveAs2 Filename:=strFolderPath & "\" & textfile, FileFormat:=wdFormatText
End With
End If
Next file
wd.Quit
Set wd = Nothing
MsgBox "処理完了"
'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True
End Sub