Fusion technology between Delphi and Word
1. Meaning of VBA code
Microsoft Word is an integrated environment and a word processing system of Microsoft Corporation in the United States. However, it is by no means just a word processing system. It integrates Microsoft Visual Basic and can extend the functions of Word through programming.
The code of Microsoft Visual Basic in Word is the macro of Word. By writing Word macros, you can realize the automation of some document processing, such as automatic backup and saving of documents, etc., which can expand the functions of Word documents. Therefore, you can make full use of Word's Features even make Word a part of its own software.
Word's macros have some benefits, because they can help us automate documents, but Word's macros are not purely beneficial. Sometimes they may harm our documents, computer systems and even networks, starting with the Taiwan NO1 macro virus The current Melissa macro virus has gone from a simple prompt at the beginning, exhausting system resources to sending random emails, sending personal information to the network, and even to the Autoexec.bat (automatic batch file) on the hard disk. Add Deltree C: -y, destroys the entire Windows system.
2. Com technology embedded in Word
It can be said that Word is the software with the best support for COM technology. It seems a bit too extreme to say this, but the powerful programming interface technology provided by Word can enable us to control any part of Word through programs. Whether it's opening, saving, printing, or automatically drawing tables in documents.
Through programming software, you can flexibly manipulate word. Here we only take Borland Delphi as an example to describe in detail:
1. How to call Word software/files in Delphi
There are three ways to call Word software in Word:
. Embedding Word through Delphi's control TOleContainer
a. Use the Servers control provided by Delphi to call Word and use the properties of Word
b. Through real Com technology, import all the class libraries in the file MSWORD9.OLB in the Office software directory into Delphi, and use Com technology to program
c. Use CreateOleObject to start Word, and then control Word in Ole mode.
2. Judgment of the difficulty of several methods
a. Embed Word through Delphi control TOleContainer
This is the simplest Ole embedding, which can directly call the Word document. You only need to use ToleContainer.Run to start the Word document directly. And the Word document started in this way is integrated with the Delphi program (from the interface point of view), but it has an insurmountable shortcoming, that is, the Word document cannot be controlled through Delphi, and the purpose of flexibly manipulating Word cannot be achieved.
b. Use the Servers control provided by Delphi to call Word and use the properties of Word
Use Delphi's Servers control to control Word. Delphi can implement code prompts during programming. Generally speaking, it can better realize Delphi's control of Word. However, there are still some functions of Word that cannot be called in Delphi (such as VBA written by yourself). macro code). And if the function is originally optional in the VBA code, the parameters must be added when calling Delphi, otherwise, even the compilation will not pass. The Word and Delphi programs started in this way belong to two forms respectively. This method can only be used as a reference.
c. Use real Com technology to import all the class libraries in the file MSWORD9.OLB in the Office software directory into Delphi, use Com technology to program, use real Com technology to import the MsWord9.OLD file class library, and then use Com technology to program use. On the whole, it is similar to using Delphi's Servers control. It is slightly more troublesome than the Servers control. The advantages and disadvantages are the same as the Servers control.
d. Use CreateOleObject to start Word, and then control Word in Ole mode.
This method is to use the CreateOleObjects method to call Word, which is actually Ole, but this method can truly fully control the Word file and use all properties of Word, including the VBA macro code written by yourself.
Compared with Servers control and COM technology, this method can truly use various properties of Word. It is basically the same as writing your own code in VBA, and there is no need to use the default code. The Word and Delphi programs started in this way belong to two forms respectively. The disadvantage is that there is no Delphi code prompt when using this method. All exception handling needs to be written by yourself, and there may be more exploratory knowledge when writing.
3. Word Macro Editor
Word can truly edit VBA code and write forms and functions.
How to enter the Word macro editor: Tools->Macros->Visual Basic Editor to enter the Visual Basic editor interface. Word's Visual Basic editor interface is basically the same as the real Visual Basic editor, so I won't go into details here. In VBA code, you can add user forms, modules, and class modules. The concepts of user forms, modules, and class modules are exactly the same as those in Visual Basic. Comments are also exactly the same as in Visual Basic.
You can place the cursor on any subroutine of the form or module and directly press "F5" to run the current subroutine.
4. Overview of Word macros
Word fully combines document editing and VB to truly automate documents. Programming using Word is similar to using Visual Basic. The difference is that in Word, you can directly run a certain subroutine and see the results directly. Word's macros can only be interpreted and run, while Visual Basic can now be written into real programs. From the perspective of code protection, the number of VBA codes in Word should be reduced as much as possible, especially the key codes.
VBA macros can be divided into four types:
1. Macro with the same name as the command
Such as FileSave, FileOpen, if the VBA code contains functions with the same name as Word, these VBA codes will be executed directly, ignoring the commands of Word itself.
2. Specific macros in Word
These macros include AutoExec (starting Word or loading global templates), AutoNew (each time a new document is created), AutoOpen (each time an existing document is opened), AutoClose (each time a document is closed), AutoExit (exiting Word or unloading global templates) hour).
If the VBA code contains functions with these names, the corresponding code will be automatically executed if the corresponding conditions are met.
3. VBA macro for corresponding events
These macros are macros triggered by events. For example, Document_Close triggers an event when the document is closed, Document_New triggers when a new document is created, and Document_Open triggers when the document is opened.
4. Independent macro
The VBA code you write yourself, that is, the VBA code that does not fall into the above situations, can be called by other VBA codes, and more importantly, can be called by other programs.
In this way, we can discard the macros automatically executed by Word and directly call the corresponding macros through Delphi to achieve the goal.
[b]5. Detailed description of Word command macros[/b]
Word itself contains a lot of command functions, but neither the Word online help nor the MSDN help provide any introduction to this aspect, so you can only explore it through your own experiments. The functions initially explored are as follows:
Macro name explanation comments
FileNew New
FileNewDefault creates a new blank document
FileSaveAs Save as
FileOpen open
FileCloseClose
FilePRint print
FilePrintPreview print preview
ToolsCustomize Customization in the toolbar
ToolsOptions tool options
ToolsRevisions Highlight revisions
ToolsReviewRevisions Accept or reject revisions
ToolsRevisionMarksAccept Accept revisions
ToolsRevisionMarksReject Reject revision
ToolsRevisionMarksToggle Revisions
ToolsMacro macro
ToolsRecordMacroToggle Record new macro
ViewSecurity Security
ViewVBCode View VB editor environment
FileTemplates templates and add-ons
ToolsProtectUnprotectDocument Unprotects the document
InsertHyperlink Insert hyperlink
EditHyperlink Edit hyperlink
DeleteHyperlink Delete hyperlink
EditLinks View and delete links
EditPasteAsHyperlink Paste hyperlink
FormatStyle style
EditBookMark bookmark
Some codes used in OleWord
1. Delphi program starts Word
Use the CreateOleObjects method to start Word and call the VBA code. The specific implementation process is:
First use GetActiveOleObject('Word.application') to determine whether there is a Word program in the current memory. If it exists, connect directly. If there is no Word program, use CreateOleObject('Word.Application') to start Word.
2. Delphi program to create a new Word document
Format: WordDocuments.Add(Template,NewTemplate,DocumentType,Visible)
Template: The name of the template to use,
NewTemplate: The type of new document, True represents a template, False represents a document
DocumentType: Document type, default is blank document
Visible: Whether the salvaged window is visible
Example: Doc_Handle:=Word_Ole.Documents.Add(Template:='C:/Temlate.dot',NewTemplate:=False);
3. Delphi program opens Word document
Format: WordDocuments.Open(FileName,ConfirmConversions,ReadOnly,PassWordDocument,
PasswordTemplate,Revent,WritePasswordDocument,WritePassWordTemplate,
Format,Encoding,Visible)
FileName: Document name (including path)
Confirmconversions: Whether to display the file conversion dialog box
ReadOnly: Whether to open the document in read-only mode
AddToRecentFiles: Whether to add files to the recently used files list at the bottom of the File menu
PassWordDocument: The password required to open this document
PasswordTemplate: The password required to open this template
Revert: If the document is already there, whether to reopen it
WritePasswordDocument: Password required to save changes to the document
WritePasswordTemplate: Saves the password required when making changes to the template
Format: The file converter needed to open the document
Encoding: The document code page used
Visible: Whether the window that opens the document is visible
Example:
Doc_Handle:=Word_Ole.Documents.open(FileName:=Doc_File,ReadOnly:=False,
AddToRecentFiles:=False);
4. Delphi program to save Word document
Format: WordDocuments.SaveAs(FileName, FileFormat, LockComments, Password,
AddToRecentFiles, WritePassword, ReadOnlyRecommended,
EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData,
SaveAsAOCELetter)
FileName: File name. Defaults to the current folder and file name.
FileFormat The format in which the document is saved.
LockComments If True, only comments are allowed on this document.
Password Password when opening the document.
AddToRecentFiles If True, adds the document to the list of recently used documents in the File menu.
WritePassword Saves the password required to make changes to the document.
ReadOnlyRecommended If True, Word will recommend read-only mode each time the document is opened.
EmbedTrueTypeFonts If True, save the document with TrueType fonts.
SaveNativePictureFormat If True, graphics imported from other system platforms (such as Macintosh) only have their Windows versions saved.
SaveFormsData If True, the data entered by the user in the form is saved as a data record.
SaveAsAOCELetter If the document contains an attachment, when this property is True, save the document as an AOCEL letter (and save the email).
Example:
Word_Ole.Documents.SaveAs(FileName:=Doc_File,FileFormat=wdFormatDocument,
AddToRecentFiles=False);
5. Read files from the database to the local hard disk and read files from the local hard disk to the database.
Use the Image binary field to save on the database and use the Stream method.
Create a file stream:
Word_FileStream:=TFileStream.Create(Target_Name,fmOpenWrite or fmCreate);
Word_FileStream.Position:=0;
Image field saved to database:
TBlobField(AdoQuery1.FieldByName(Column_Name)).SaveToStream(Word_FileStream);
Read files from database to local hard disk:
TBlobField(ADOQuery1.FieldByName(Column_Name)).loadfromStream(Word_FileStream);
Release the file stream:
Word_FileStream.Free;
6. Definition of global message
Because word and Delphi programs are two software, it is troublesome to communicate with each other, so the global message method is used. Global messages must be registered first, and Windows returns the system's idle message number. When the registered messages are the same, the Windows system returns the same value, thus ensuring that this message number is used to communicate between two programs.
How to define a message:
szMessageString: pchar = 'XIDIAN_11_Stone';
FMyJoinMessage := RegisterWindowMessage(szMessageString);
How to send a message:
SendMessage (other party handle, message, message comes with short variables, message comes with long variables)
7. How the Delphi program receives messages
There are two types of messages received by Delphi. One is to overload a specific message, and the other is to overload the WndProc function and select the corresponding message for processing.
Method one can only process one message at a time, while method two can process multiple messages at the same time.
For method two, the statement is as follows:
procedure WndProc(var Message: Tmessage);override
It must be noted that when using it, you need to inherit the WndProc(Message) function after processing your own message, otherwise the system will crash!
8. Dynamic generation of Combo dialog box and Change event in Word
Create the class module Combohander and define events internally
Public WithEvents ComboBoxEvent As Office.CommandBarComboBox
Define the module that generates events for the Combo control
Dim ctlComboBoxHandler As New ComboBoxHandler
Generate Combo dialog box
Set Cbo_ChooseDoc = CommandBars("Added Menu").Controls.Add(Type:=msoControlComboBox, Temporary:=True)
Set the file handle to generate the Combo_Change event
Set ctlComboBoxHandler.ComboBoxEvent = Cbo_ChooseDoc
After the event is generated, select the Change event of ComboBoxEvent in the class module Combohander to write the event code
Sub ComboBoxEvent_Change(ByVal Ctrl As Office.CommandBarComboBox)
9. Some Word events
The Word events handled in VBA code are: Document_Close
What needs to be processed in the Application event are: DocumentBeforeClose, DocumentChange.
Document_Close: event generates an event when the document is closed
DocumentBeforeClose: Before the document is closed, Word determines whether the document is saved, gives corresponding prompts, and performs corresponding processing.
DocumentChange: Document switching. Events are generated when the document is switched between the document modified by oneself and the document modified by others. It mainly handles setting document permissions, etc.