Перейти к основному содержанию

Как пакетно конвертировать документы Word в текстовый файл?

В этой статье рассказывается о том, как пакетно преобразовать все документы Word в определенной папке в отдельные файлы TXT в Word.

Пакетное преобразование документов Word в файлы txt с помощью VBA


Пакетное преобразование документов Word в файлы txt с помощью VBA

Приведенный ниже код VBA может помочь преобразовать все документы Word в определенной папке в файлы txt сразу. Пожалуйста, сделайте следующее.

1. В документе Word нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модули, затем скопируйте приведенный ниже код в окно модуля.

Код VBA: пакетное преобразование документов Word в файлы txt

Sub ConvertDocumentsToTxt()
'Updated by Extendoffice 20181123
    Dim xIndex As Long
    Dim xFolder As Variant
    Dim xFileStr As String
    Dim xFilePath As String
    Dim xDlg As FileDialog
    Dim xActPath As String
    Dim xDoc As Document
    Application.ScreenUpdating = False
    Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xDlg.Show <> -1 Then Exit Sub
    xFolder = xDlg.SelectedItems(1)
    xFileStr = Dir(xFolder & "\*.doc")
    xActPath = ActiveDocument.Path
    While xFileStr <> ""
        xFilePath = xFolder & "\" & xFileStr
        If xFilePath <> xActPath Then
            Set xDoc = Documents.Open(xFilePath, AddToRecentFiles:=False, Visible:=False)
            xIndex = InStrRev(xFilePath, ".")
            Debug.Print Left(xFilePath, xIndex - 1) & ".txt"
            xDoc.SaveAs Left(xFilePath, xIndex - 1) & ".txt", FileFormat:=wdFormatText, AddToRecentFiles:=False
            xDoc.Close True
        End If
        xFileStr = Dir()
    Wend
    Application.ScreenUpdating = True
End Sub

3. нажмите F5 ключ для запуска кода.

4. в ЛИСТАТЬ СПИСКИ в окне выберите папку, содержащую документы Word, которые вы конвертируете в текстовые файлы, и щелкните значок OK кнопка. Смотрите скриншот:

После этого вы увидите, что все документы в выбранной папке сразу конвертируются в текстовые файлы. Смотрите скриншот:

Лучшие инструменты для офисной работы

Kutools for Word - Повысьте свой опыт работы со словом с помощью Over 100 Замечательные особенности!

🤖 Kutools AI Помощник: Преобразуйте свое письмо с помощью искусственного интеллекта. Создать контент  /  Переписать текст  /  Обобщение документов  /  Запросить информацию на основе документа, все в Word

📘 Владение документами: Разделить страницы  /  Объединить документы  /  Экспортировать выбранное в различные форматы (PDF/TXT/DOC/HTML...)  /  Пакетное преобразование в PDF  /  Экспортировать страницы как изображения  /  Печать нескольких файлов одновременно...

Редактирование содержания: Пакетный поиск и замена через несколько файлов  /  Изменить размер всех изображений  /  Транспонировать строки и столбцы таблицы  /  Преобразовать таблицу в текст...

🧹 Легкая очистка: Убрать Дополнительные места  /  Разрывы разделов  /  Все заголовки  /  Текстовые поля  /  Гиперссылки  / Чтобы получить дополнительные инструменты для удаления, посетите наш Удалить группу...

Креативные вставки: Вставлять Разделители тысяч  /  Флажки  /  радио кнопки  /  QR код  /  Штрих-код  /  Таблица диагональных линий  /  Заголовок уравнения  /  Заголовок изображения  /  Заголовок таблицы  /  Несколько изображений  / Узнайте больше в Вставить группу...

???? Точный выбор: Точно определить конкретные страницы  /  Эта таблица  /  формы  /  заголовки абзацев  / Улучшите навигацию с помощью БОЛЕЕ Выберите функции...

Звездные улучшения: Быстро перемещайтесь в любое место  /  автоматическая вставка повторяющегося текста  /  плавно переключаться между окнами документов  /  11 инструментов преобразования...

👉 Хотите попробовать эти функции? Kutools for Word предлагает 60-дневная бесплатная пробная версия, без ограничений! 🚀
 
Comments (22)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
Vielen Dank, das ist wirklich sehr hilfreich! Ich werde auf Deine Seite bei der nächsten Gelegenheit verweisen.
Gruß
Uli
This comment was minimized by the moderator on the site
Hi, this works perfectly. Is there a way to choose a different encoding format of the TXT (UTF-8 instead of Windows for example) ?
This comment was minimized by the moderator on the site
Hi Simon,
The following VBA code helps to convert all Word documents in a specified folder to UTF-8 .txt files
Sub ConvertDocumentsToTxt()
'Updated by Extendoffice 20201031
    Dim xIndex As Long
    Dim xFolder As Variant
    Dim xFileStr As String
    Dim xFilePath As String
    Dim xDlg As FileDialog
    Dim xActPath As String
    Dim xDoc As Document
    Application.ScreenUpdating = False
    Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xDlg.Show <> -1 Then Exit Sub
    xFolder = xDlg.SelectedItems(1)
    xFileStr = Dir(xFolder & "\*.doc")
    xActPath = ActiveDocument.Path
    While xFileStr <> ""
        xFilePath = xFolder & "\" & xFileStr
        If xFilePath <> xActPath Then
            Set xDoc = Documents.Open(xFilePath, AddToRecentFiles:=False, Visible:=False)
            xIndex = InStrRev(xFilePath, ".")
            xDoc.SaveAs Left(xFilePath, xIndex - 1) & ".txt", FileFormat:=wdFormatText, AddToRecentFiles:=False, Encoding:=msoEncodingUTF8
            xDoc.Close True
        End If
        xFileStr = Dir()
    Wend
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Merci beaucoup ! La conversion se fait très bien
This comment was minimized by the moderator on the site
Many thanks
This comment was minimized by the moderator on the site
Hello, Thank you for this post. When I hit "run", I get an error message:"Compile Error: Invalid Outside Procedure." This is whether I use the doc or the docx extension (maybe unrelated but I tried both.) Please can you help? I have no idea how to use code.... and really need to convert a ton of docs. Thank you!
This comment was minimized by the moderator on the site
Hi Durga,
The code works well in my case.
Please make sure that the Module (Code) window contains only the VBA code provided in the post.
This comment was minimized by the moderator on the site
That worked a treat! Thanks!
Rated 5 out of 5
This comment was minimized by the moderator on the site
I NEED them to convert to delimited text files is this possible still.
This comment was minimized by the moderator on the site
I used the script above to batch convert documents in Korean, but the script did not work. When I tired to change the encoding, Can anyone help me with this error?
This comment was minimized by the moderator on the site
Thanks for this - I was just going to code something myself when I thought, "Hey perhaps someone has done this already?" You had, and a deal more elegantly than I would have done. Thanks you for your hard work.
This comment was minimized by the moderator on the site
The script works great for me, but only for one folder. Is there any way to include all subfolders?
This comment was minimized by the moderator on the site
Thank you a lot! Worked like a charm!
This comment was minimized by the moderator on the site
Worked rapidly and perfectly on a folder full of .docx files. I thank you/
This comment was minimized by the moderator on the site
Hi, the code works but at the end gives me 'Runtime error 91', some of my files have objects. Any idea how can I fix this?
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations