Windows Batch File: Merge all .docx files in current folder?

Solution 1:

You don't need to print the file names to a text file just to read it back. You can just collect the names in a variable with a for loop.

This script should work:

@echo off & setlocal enabledelayedexpansion
cd %1
set files=

for %%i in (*.docx) do set files=!files! "%%i"

DocxMerge.exe -i %files% -o "%~n1.docx"

It expects the folder containing the .docx files as its first and only argument, which means you can just drag-and-drop the folder onto the batch file.

The name of the folder given in the argument will be used as the name of the output file. This is achieved by expanding the argument to a file name only with %~n1.

If you want to place the batch file in the folder containing the .docx files and not use an argument you can obtain the name of the current folder with

set name=
for %%i in (.) do set name=%%~nxi

If the files are processed in the wrong order you can reverse the order by replacing set files=!files! "%%i" with set files="%%i" !files!.

Edit:

The wrong order definitely sounds like a bug in DocxMerge. You can work around that by storing the first file in a seperate variable and then prepending that value to the rest of the files after the for loop:

@echo off & setlocal enabledelayedexpansion
set files=
set firstFile=

for %%i in (*.docx) do (
    if [!firstFile!]==[] (
        set firstFile="%%i"
    ) else (
        set files="%%i" !files!
    )
)
set files=%firstFile% %files%

set name=
for %%i in (.) do set name=%%~nxi

DocxMerge.exe -i %files% -o "%name%.docx" -f

To delete the result of previous merges so it isn't included in a new merge just move

set name=
for %%i in (.) do set name=%%~nxi

above the for loop and add if exist "%name%.docx" del "%name%.docx"

Solution 2:

I have a folder which has many subfolders in it containing Word documents. I want to merge Word documents within a each folder and then merge the resulted merged documents created in each of folders into one large document.

The below code is merging documents in a folder and when I perform a loop and add this above for loop to go in each subfolder and create separate merged document, it says "-i is required". Why do I get this message?

code below:

@echo off & setlocal enabledelayedexpansion

set /A C=0    
FOR /R %%a in (.) do (    
  pushd %%a    
  echo In directory:    
  cd    
  SET firstFile=    
  SET files=

  FOR %%X in (*.docx) DO (    
  IF [!firstFile!]==[] (    
          SET firstFile="%%X"    
    ECHO yes        
      ) ELSE (    
          SET files="%%X" !files!       
    ECHO next    
      )    
   )

   ECHO ifclose    
     SET files=%firstFile% %files%    
 set /A C=C+1

 DocxMerge.exe -i %files%  -o "doc%C%.docx" -f

 pause    
 rem leave the directory    
 popd    
 pause    
)