Fusion Technology between Delphi and WORD
Author: cwxiao888 Source: fusion between 9CBSDelphi and a Word, VBA meaning of the code Microsoft Word is an integrated environment is Microsoft's word processing system of the United States, but it is much more than a word processing system, which integrates Microsoft Visual Basic, can be programmed to extension to Word features. Microsoft Visual Basic's code in Word is the macro of Word, by writing a Word macro, can implement some document processing, such as automatic backup, storage, etc. to implement documents, can extend the function of the Word document, so it can make full use of Word Features, even make Word a part of our software. Word's macro is only part of it, because it can help us achieve the automation of documents, but Word's macro is not purely beneficial, sometimes it may endanger our documentation, computer system and even network, from the most beginning TAIWAN NO1 macro virus Go to the current Melissa macro virus, from the starting simple tips, exhaust the system resources to the current e-mail, send personal information to the network, even to the hard disk's autoexec.bat (automatic batch file) Add DELTREE C: -Y to destroy the entire Windows system. Second, COM technology in Word can say that Word is the best software for COM technology, which seems to be too extreme, but the powerful programming interface technology provided by Word can be any of our controlled Word. Part. Whether it is the opening of the file, the storage, printing is the automatic drawing of the table in the document. By programming software, you can flexible manipulation of Word, which is only described in detail with Borland Delphi: 1. Calling Word Software / files in Delphi, calling Word software in Word, summarizing three methods:. Tolecontainer through Delphi to embed Word into a. Call Word using the Servers control provided by Delphi, using the word attribute B. By real COM technology, put all the libraries in the office software in the office software msword9.olb into Delphi, using COM technology programming c. Word will start using CreateoleObject, and then control Word in OLE mode. 2. Difficult to discriminate a few ways a. Controls toleContainer through Delphi to embed this is the simplest OLE embedding, can call the Word document directly, just use toleContainer.run to start the Word document directly . And the Word document with this started and the delphi program is a whole (see on the interface), but it does not overcome the shortcomings, that is, the Word document cannot be controlled by Delphi, and cannot be flexible to manipulate the purpose of Word. b. Calling Word using the Servers control provided by Delphi, using the attribute of the Word to manipulate the word, when programming, Delphi can implement code prompt, overall, can better implement Delphi's control for Word, but there are Some Word features cannot be called in Delphi (such as the VBA macro code written). And when implementing functions, the optional parameters in the VBA code must be added at the Delphi call, otherwise, even compilation cannot pass. The Word and Delphi program initiated in this way are two forms. This method can only be used as a reference.
c. Through the real COM technology, all the class libraries in the Office software catalog in the Office software directory into Delphi, using COM technology to program the real COM technology, use the MSWORD9.OLD file class library, then use COM technology to carry out use. The whole is similar to the Servers control using Delphi, a bit more troublesome than the Servers control, the advantages and disadvantages are the same as the Servers control. d. Use CreateoleObject will start Word and then control the Word in an OLE mode. This method is to use the CreateoleObjects mode to call Word, actually OLE, but this way can truly control the Word file, you can use all properties of Word, including your own VBA macro code. Compared with the Servers control and COM technology, this method can truly use the various properties of Word, and the code that is written in VBA, the default code is not required. The Word and Delphi program initiated in this way are two forms. The disadvantage is that the use of this method has no Delphi code prompts, all exception processing requires yourself, and there may be more exploratory knowledge when writing. Third, the Word Macro Editor Word can really perform the editing of VBA code, you can write forms, functions. Methods of entering the Word Macro Editor: Tools -> Macro -> Visual Basic Editor, you can enter the Visual Basic editor interface. The Word's Visual Basic editor interface and the real Visual Basic editor are basically the same, and this is no longer detailed. In VBA code, you can add user forms, modules, class modules. The concept of user form, module, class module is identical, and Visual Basic. The comments are also identical to Visual Basic. The cursor can be done on any subroutine of the form and module, press "F5" to run the current subroutine directly. 4. Overview of Word Macros WORD fully combines document editing and VB to truly implement the documentation. Using Word Programming, similar to using Visual Basic, where is in Word, you can directly run a subroutine, see the result, Word's macro, can only interpret the run, and Visual Basic, now you have written into true The machine code, from the code of the code, should reduce the number of Word's VBA code, especially the critical code as much as possible. The VBA macro can be divided into four: 1, and the same macro, FileSave, FileOpen, which contains the same name with Word in the VBA code, and ignore the Word itself command. 2, Word's specific macro these macro contains AutoExec (starting Word or load global template), AutoOpen (when new documentation), AutoOpen (time to open an existing document), AutoExit (When you exit Word or uninstall global template). If the VBA code contains a function of these names, the corresponding condition is met, the corresponding code is automatically executed. 3, the VBA macro of the corresponding event is a macro triggered by an event. If Document_Close triggers events when the document is turned off, Document_New is triggered when the document is created, and Document_Open triggers when the document is opened.
4, the independent macro you wrote the VBA code, that is, the VBA code that is not above the above case, can be called by other VBA code, more importantly, can be called by other programs. In this way, we can discard the macro executed by Word, and call the corresponding macro directly through Delphi to achieve the purpose.
[B] V. Detailed Description of Word Command Macro [/ b] The command function of Word itself contains a lot, but whether it is Word online help or MSDN help, there is no introduction in this regard, so it can only explore its own experiment. function preliminary probe follows: macro name interpreted comments FileNew New FileNewDefault New blank document FileSaveAs Save as FileOpen open FileClose close FilePrint print FilePrintPreview Print preview ToolsCustomize toolbar inside custom ToolsOptions tool options ToolsRevisions highlight Changes ToolsReviewRevisions Accept or reject Changes ToolsRevisionMarksAccept accept the amendment ToolsRevisionMarksReject reject changes ToolsRevisionMarksToggle revised ToolsMacro macro ToolsRecordMacroToggle record new macro ViewSecurity security ViewVBCode view the VB editor environment FileTemplates templates and add-ins ToolsProtectUnprotectDocument unprotect InsertHyperlink of the document into hyperlinks EditHyperlink edit hyperlinks DeleteHyperlink delete hyperlinks EditLinks view, delete links EditPasteAsHyperlink Paste Hyper Link FormatStyle Style EditBookmark Bookmark OleWord When you use code, the Delphi program launches Word to start Word, call VBA code, the specific implementation process is: First use getActiveoleObject ('word.application') to determine the current memory Whether there is a Word program, if there is, it is directly connected. If there is no Word program, use CreateoleObject ('Word.Application') to start the Word 2, Delphi program New Word document format: WordDocuments.Add (Template, NewTemplate, DocumentType, Visible Template: Name of the template, newTemplate: Type of New Document, True Indicated as a template, false is represented as a document DocumentType: Document type, default is a blank document Visible: Savings window can be seen: doc_handle: = word_ole.documents.add (Template: = 'C: /TemLate.dot', Newtemplate: = False); three, Delphi program to open Word document format: WordDocuments.Open (FileName, ConfirmConversions, ReadOnly, PassWordDocument, PasswordTemplate, Revent, WritePasswordDocument, WritePassWordTemplate, format, Encoding, Visible) FileName: document name (including path) Confirmconversions: whether File Translation dialog readonly: Do you open a document in read-only mode: Do you add a file to the recently used file list of the file at the bottom of the file: PasswordDocument:
PasswordTemplate required when opening this document: The password required when opening this template: If the document is already, you reopen the document WritePasswordDocument: Save the password written when the document change is written WritePasswordTemplate: Save the template to change the template Password Format: File converter Encoding when you open a document: Document code page Visible: Open the window of the document can be seen: doc_handle: = word_ole.documents.open (filename: = DOC_FILE, READOC = FALSE, AddToRecentFiles: = False); four, Delphi program save Word presentation format: WordDocuments.SaveAs (fileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter) fileName: file name. The default is the current folder and file name. FileFormat document saved format. Lockcomments If you are True, this document only allows annotations. Password opens the password when documentation. AddTorecentFiles If true, add a document to the "File" menu in the list of documents. WritePassword saves the password required to modify the document. ReadonlyRecommended If you are True, Word will recommend a read-only mode when you open a document each time you open a document. EmbedTrueTypefonts If you are TRUE, you save the document with the TrueType font. SavenativePictureFormat If true, the graphically imported graphics imported from other system platforms (such as Macintosh) only saves its Windows version. SaveFormsData If True, save the data in the form into a data record. SaveASaocletter If the document contains an additional, when this property value is TRUE, the document is saved as an AOCE letter (simultaneously). Example: Word_ole.documents.saveas (files: = doc_file, flyformatfiles = false); 5. Read files from the database to your local hard drive and read files from the local hard drive to the database to save on the database. Use the Stream stream.
Create a file stream: Word_FileStream: = TFileStream.Create (Target_Name, fmOpenWrite or fmCreate); Word_FileStream.Position: = 0; save the Image field in the database:. TBlobField (AdoQuery1.FieldByName (Column_Name)) SaveToStream (Word_FileStream); read from the database Take a document to the local hard drive: TBLOBFIELD (COLUMN_NAME)). LoadFromStream (Word_FileStream); Release file stream: Word_FileStream.free; 6 Trouble, so the method of using global messages. Global message must first register, Windows returns the message number of the system, when the registered message is the same, the Windows system returns the same value, which ensures that the message number is communicating between the two programs. Measures for defining messages: pchar = 'xidian_11_stone'; fmyjoinMessage: = registerWindowMessage (szMessageSTRING); Send message method: sendMessage (other handle, message, message with short variable, message with long variable) Seven, Delphi program receives messages Method DELPHI receives the message has two, one is to overload a specific message, and the other is to overload the WndProc function, and select the corresponding message inside. Fifth, only one message can be handled each time, and the second can handle multiple messages simultaneously. For the method, the declaration is as follows: Procedure WndProc (Var message: tMessage); Override must pay attention to the WndProc (Message) function after processing your message processing, otherwise the system will crash! Eight, in Word Combo dialog dynamically generated, and the establishment of the Change event class module Combohander, the event generating module Dim ctlComboBoxHandler As New ComboBoxHandler produce Combo box Set Cbo_ChooseDoc = CommandBars within the defined events Public WithEvents ComboBoxEvent As Office.CommandBarComboBox defined Combo Control ( "Add menu") .Controls.Add (type: = msoControlComboBox, Temporary: = True) for file handles set to produce Combo_Change event set ctlComboBoxHandler.ComboBoxEvent = Cbo_ChooseDoc after generating events, select ComboBoxEvent in the class module Combohander Change event Keep writing event code Sub ComboBoxEvent_change (Byval Ctrl As Office.commandbarCombox) Nine, some Word events in the Word event VBA code are: DocumentBeforeClose, DocumentChange, which requires: DocumentBeforeClose, DocumentChange.
Document_close: Events Generate Event DocumentBeforeClose when the document is turned off: Before the document is turned off, the Word determines whether the document is saved, gives the corresponding prompt and processed accordingly. DocumentChange: Document Switching, switching between documents to switch between documents and other documents modified by other people, primarily handle setting document permissions, etc.
http://www.zhbook.com/show.asp?id=36