将文本文件转换为Word docx

时间:2014-09-05 23:10:15

标签: vba batch-file docx

我需要将文本文件(.txt)转换为MS Word文档(.docx)的VBA代码。有没有人有代码来完成这个?我在目录中有许多文本文件,并希望使用相同的目录名将它们批量转换为同一目录或VBA创建的目录中的docx文件,并使用"转换"添加到目录名称。我有超过800个txt文件要转换。

谢谢你, 纳尔逊

2 个答案:

答案 0 :(得分:0)

您可以通过记录导入文本文件的步骤并将其保存到Excel(xls,xlsx)文件,在Excel中创建VBA脚本/宏。我用Excel完成了这项工作,但Word具有类似的录制/宏功能。

答案 1 :(得分:0)

Here我创建了一个完全相反的脚本。这是一个从docx创建txt的重写版(它是一个vbscript / batch hybrid,需要是保存为.bat需要管理员权限(主要是为了启动隐形字):

'>nul 2>&1|| @copy /Y "%windir%\System32\doskey.exe" "'.exe" >nul
'&&@echo off && cls &&goto :end_vbs

Set WordApp = CreateObject("Word.Application")
WordApp.Visible = FALSE

'Open txt for reading
Set WordDoc = WordApp.Documents.Open(WScript.Arguments.Item(0),false)

'wdFormatText 2
'wdFormatUnicodeText 7
'wdFormatDocumentDefault 16
'http://msdn.microsoft.com/en-us/library/office/ff839952.aspx



WordDoc.SaveAs WScript.Arguments.Item(1) ,16 
WordDoc.Close()
WScript.Quit

:end_vbs

'& if "%~1" equ "-help" echo %~n0 text_document [ destination ]
'& if "%~1" equ "" echo txt document not given & exit /b 1
'& if not exist "%~f1" echo txt document does not exist & exit /b 2
'& if "%~2" equ "" ( set "save_as=%~dpn1.docx") else ( set "save_as=%~2")
'& if  exist "%~f2" del /s /q "%~f2"
'& for  %%# in ("%save_as%") do set "save_as=%%~dpn#"
'& taskkill /im winword* /f >nul 2>&1
'& cscript /nologo /E:vbscript %~f0 "%~f1" "%save_as%" 
'& pause
'& rem del /q '.exe 

可能是我应该创建一个jscript / bat混合代码,因为代码会更方便... 无论如何,这接受2个参数用于.txt文件,一个用于.docx desination,但txt文件将保持未删除。您可以使用它来迭代您的txt文件转换并删除它们

相关问题