Location>code7788 >text

Merge Word documents with text boxes: VBA code batch operations

Popularity:441 ℃/2024-11-16 16:24:01

  This paper describes a system based onVBAlanguage, for a large number of images, text boxes and tables containingWordDocuments are automatically merged in batches, and at each mergeAdding page breaksThe methodology.

  In our previous post, we described the process of creating an application based on thePythonlinguisticpython-docxdocx) module withdocxcomposemodule for a large number ofWordmethod of merging documents; however, based on this method, we were not able toText box with unspecified size(used form a nominal expression)Wordto be merged, aspython-docxUnable to process elements containing suchWordDocumentation. Recently, an older brother proposed mergingContains a text box(used form a nominal expression)Wordneeds, so just try to use theVBAto accomplish this operation, and here's how to do it.

  Among them.VBAis an acronym for Visual Basic for Applications, which is based on theVisual BasicAn extension of the language, mainly used in MicrosoftOfficeVarious applications in the suite, such asWordExceltogether withPowerPointetc.; it allows users to create customized macros and applications to automate a variety of tasks to increase productivity. Currently.VBAIt is mainly used for batch operation.Officedocuments in various scenarios.

  The requirement of this paper is as follows. Now there is a folder, which contains a large number of document files, as shown in the following figure; where, in each document, contains images, tables, text boxes, and so onMore complex elements

image

  We now want to be able to batch merge a large number of document files in a folder; and when doing so, each time we need to add a new file in the new1page to merge the next file (i.e., the contents of the different files should not appear in the1(Page in).

  Once the requirements are clear, you can start writing the code. The code required for this article is as follows.

Sub merge_word()
    Dim time_start As Single: time_start = Timer
    Dim word_result As Document
    Dim word_temp As Document
    Dim file_dialog As FileDialog
    Dim str As String
    Dim file
    Dim num As Long
    
    Set word_result = ActiveDocument
    Set file_dialog = (msoFileDialogFilePicker)
    
    With file_dialog
        .AllowMultiSelect = True
        .Title = "please select【One or more】Files that need to be merged with the current document"
        With .Filters
            .Clear
            .Add "Wordfile", "*.doc*;*.dot*;*.wps"
            .Add "所有file", "*.*"
        End With
        If .Show Then
             = False
            num = .
            For Each file In .SelectedItems
                Set word_temp = (file)
                word_temp.
                
                word_result.Range(word_result. - 1, word_result.).Select
                
                DoEvents
                
                
                
                word_temp.Close wdDoNotSaveChanges
            Next
            
             = True
        End If
    End With
    
    Set word_result = Nothing
    Set word_temp = Nothing
    Set file_dialog = Nothing
    
    str = Format(Timer - time_start, "All have been successfully merged;commons0unit of angle or arc equivalent one sixtieth of a degree!")
    str = Format(num, "You choose to merge0个file,") & str
    MsgBox str, vbInformation, "file合并结果"
End Sub

  In the above code, we first perform thevariable declarationtime_startanSingletype variable to record the time when the code started executing;TimerThe function returns a single-precision floating-point number representing the number of seconds that have elapsed since the computer was started.word_resultanDocumentvariable to store the currently openedWordDocumentation.word_tempIt's another one.Documenttype variable to temporarily store the other variables to be merged.WordDocumentation.file_dialoganFileDialogVariable of type to store the file selection dialog box object.stris a variable of string type to store the final merge result information to be displayed in the message box.fileUsed to store each file path selected by the user in a loop.numis a long integer variable that stores the number of files selected by the user.

  We thenGet the current document. Sets the currently edited version of theWordDocument Assignmentword_resultvariable, this document is the resulting document that will merge the contents of the other documents.

  Next.Open the file selection dialog box.. Create a file selection dialog object and set the properties of the dialog one by one; among them, allow the user to select multiple files, customize the title of the dialog, and set the file type filter, where the first one indicates that only displaying theWorddocument files, and the second indicates that all types of files are displayed.

  Immediately following the passage ofIf .Show Thenstatement that determines whether the user has selected a file in the dialog box. If so, perform a merge operation. In this case, first the number of files selected by the user is obtained; subsequently, a loop traverses each selected file - opening each selected file as ainterim documentwillinterim documentto the clipboard; position the cursor in thetarget document(a.k.a. the result file) at the last character and paste the contents of the clipboard into thetarget documentand insert a page break after the pasted content; finally, close theinterim documentwithout saving the changes. Next, the next traversal is performed. One of the things to note here is that if we don't add theDoEventsThis code, which causes the code below it toThis code reports an error (although it will report an error, but in fact, after selecting debugging and continuing to press theF5(and the program still runs).

  Finally, you can clean up the variable references and calculate the elapsed time of the merge operation, displaying the result information in a message box.

  The code is executed as follows. First, create a blank path in anyWorddocument as our results file. Subsequently, in this document, simultaneously press theAltchemical bond withF11key to enter theVBAMacro interface, as shown in the following figure.

  Subsequently, in the upper left corner of theNormalRight click and select "stick”→“module (in software)", as shown below.

  Subsequently, in the pop-up window, copy the aforementioned code as shown below.

  Next, pressF5key, you can start running the code. Among them, the first pop-up window to select a file, we select the file to be merged can be; as shown in the figure below.

  Afterwards, click on "recognize", you can start merging files. Wait for a few moments, the merge will be completed and the interface will pop up as shown below.

  At this point, back to our openWordfile, you can see that the files have been merged in.

  Among them, the area shown in the purple box in the picture above is the beginning part of the file to be merged here (the red two-segment line in the purple box is only to cover some of the information in the file, there is no other meaning, we can understand it) - you can see that each time a new file merge is operated on a new page, which meets our needs .

  At this point, the job is done.