Ya que tocamos a Excel

717 views
Skip to first unread message

Harold San Lee

unread,
May 17, 2023, 11:50:09 AM5/17/23
to harbou...@googlegroups.com
Ya que estamos tocando la programación Harbor con excel , tengo una pregunta para el grupo:
alguien ha hecho algo de programación Harbour y/o GUI para desarrollar Tablas Dinámicas Excel? 

Lo estoy intentando pero no he podido con Qpm +oohg + mingw .


Muchas Gracias

E.Harold San Lee

Bernard Mouille

unread,
May 18, 2023, 1:42:46 AM5/18/23
to Harbour Users
Hello,
Maybe you can take some idea in the attached code.
Regards,
Bernard.

Test.txt

Harold San Lee

unread,
May 18, 2023, 12:25:53 PM5/18/23
to harbou...@googlegroups.com

Regards Bernard,


Thank you very much for your quick response, I will try it.



E. Harold San Lee


--
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
Unsubscribe: harbour-user...@googlegroups.com
Web: https://groups.google.com/group/harbour-users
---
You received this message because you are subscribed to the Google Groups "Harbour Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to harbour-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/harbour-users/8c9a31a0-9b50-42c0-9f3f-6dff1df58aedn%40googlegroups.com.

Bernard Mouille

unread,
May 18, 2023, 2:15:40 PM5/18/23
to Harbour Users
Hello,
If you want, I have a code who use a dbf table transformed.
Regards,
Bernard.

Harold San Lee

unread,
May 18, 2023, 6:18:43 PM5/18/23
to harbou...@googlegroups.com
Hello Bernard,

I am interested in the code you have where you use a transformed dbf table.

Greetings,
E. Harold San Lee

Bernard Mouille

unread,
May 18, 2023, 11:56:07 PM5/18/23
to Harbour Users
Hello Harold,

Attache the code to use with a transformed dbf table.
If you use MySql, I think that you can create the dynamic cross pivotable directly, look at Microsoft.

Regards,
Bernard.
Test.txt

Harold San Lee

unread,
May 19, 2023, 10:06:21 AM5/19/23
to harbou...@googlegroups.com
Hello Bernard,

Thank you very much for such an excellent contribution, interesting to know how harbor integrates with ms excel.

Greetings
E. Harold San Lee.

Jayadev U

unread,
May 19, 2023, 10:29:56 AM5/19/23
to harbou...@googlegroups.com

Excellent code Bernard,  you amaze me.

 

Hope you are storing all this code on your website for use of posterity.

 

Warm regards,

 

Jayadev

Bernard Mouille

unread,
May 19, 2023, 12:11:32 PM5/19/23
to Harbour Users
Hello Jayadev,

Thanks for your congratulations.
I have puts the links where I have found the way and I have only translate and modify for Harbour.
If the table has not fields types MEMO or LOGICAL, you can open directly the dbf table, create the first pivotable from and create the pivotable cross dynamic.
I am playing to find another way with the pivotables.
My web site is not up-to-date.

Regards,
Bernard

Francesco Cersosimo

unread,
May 20, 2023, 3:50:29 PM5/20/23
to Harbour Users
Very good I say Superlative with the code for Excel. I ask you for help if you have prepared a test file for Word. Thanks Infinite.
Franco Harbour amateur

Bernard Mouille

unread,
May 22, 2023, 2:50:16 AM5/22/23
to Harbour Users
Hello Francesco,
Thanks for your comment.
What do you need to do with Word for your first test ?
Microsof Office ( and Apache Libre Office ) has a very lot of possibility.
Regareds,
Bernard.

Francesco Cersosimo

unread,
May 22, 2023, 7:57:03 AM5/22/23
to Harbour Users
Very kind. Only for Microsoft Word, I don't use anything else I would need an example to export data from dbf table to word table. Common text from txt file with the instructions to manage the insertion of a string, the insertion of a paragraph, then the management of line insertion, paragraph, table data, and of course the font and color codes, opening and closing of the file word. If possible the modification of an existing word file with the insertion and addition of text in string and paragraphs ... I do not know VBA for Word if possible everything that can be done in VBA always from Microsoft instructions in Harbor for WORD . Thanks for your kind attention and, given your special skill, I'm sure you've already achieved all this. With deep admiration and esteem, I remain at your complete disposal for any need. Thank you so much.
Franco Harbor Amateur

Bernard Mouille

unread,
May 23, 2023, 3:55:35 PM5/23/23
to Harbour Users
Hello Francesco,

Attached a code to put an excel sheet in a Word document.
Replace 
oBook  := oExcel:Workbooks:Open( BM_FILE_EXCEL )
with
oBook  := oExcel:Workbooks:Open( YourDbfTable )

For the color and the text, you can modify the Excel sheet.

For understand that you need exactly, post :
- a sample dbf table,
- a sample Word file.

Regards,
Bernard.
Test.txt

Francesco Cersosimo

unread,
May 23, 2023, 6:45:53 PM5/23/23
to Harbour Users

Brilliant Bernard, from excel to word I hadn't thought of that and I thank you so much for your contribution. Instead, I meant from the contribution for Word that he provided in the link that I point out to you:

multi images detecting inside word document (google.com)

Many thanks for your kind cooperation,

Greetings

Franco Harbour Amateur

Brilliant Bernard.docx

Bernard Mouille

unread,
May 25, 2023, 3:06:07 AM5/25/23
to Harbour Users
Hello Francesco,
The sampleto insert text from file into a word document.
For the dbf, i do ASAP but I am busy now.
Regards,
Bernard.

// Begin code.
/*
   MW_InsertTextFromTxtFile.prg
   Sample to instert text from txt file with MS Word file.
   Using HB32, Windows10, MS Word 2007.

   Compile with -lhbwin -lhbmisc

   This code is a basic sample for tests.

   Copy the constants files from my web site.

   web : http://bernard.mouille.free.fr/mso-hb32/MW_InsertTextFromTxtFile.txt
   Last change : 2023-05-25
*/

// Parameter.
#define BM_FILE_WORD hb_dirbase() + "_Result_Word.docx"         // File to create with his path.
#define BM_FILE_TXT  hb_dirbase() + "_Result_Txt.txt"           // File to insert in the document.

#include "mw_WordConstants.h"    // http://bernard.mouille.free.fr/mso-hb32/mw_WordConstants.h
#include "bh_rgbColors.h"        // http://bernard.mouille.free.fr/mso-hb32/bh_rgbColors.h

procedure Main
   local i              // Count number.
   local oWord          // Word object.
   local oDoc           // Document object.
   local oSele          // Selection object.
   local aLines         // Text array lines to insert

   setmode( 25, 80 )
   setcolor( "GR+/B" )
   @ 0, 0, maxrow(), maxcol() box space( 9 )

   ? "Sample to instert text from txt file with MS Word file."

   ferase( BM_FILE_WORD )
   CreateTestTxtFile( BM_FILE_TXT )

   oWord         := win_olecreateobject( "Word.Application" )
   oWord:Visible := .T.
   oDoc          := oWord:documents:add()
   oWord:ActiveDocument:Select()

   // Option : Page number at the end of page.
   oDoc:Sections( 1 ):Footers( wdHeaderFooterPrimary ):PageNumbers:Add()

   // Option : Margins.
   oDoc:PageSetup:LeftMargin   := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:RightMargin  := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:TopMargin    := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:BottomMargin := oWord:Application:CentimetersToPoints( 1 )
   oSele := oWord:Selection

   oWord:Selection:typetext( "Instert text from txt file with MS Word file" )
   oWord:Selection:InsertBreak( wdLineBreak )

   oSele:TypeParagraph()
   oSele:typetext( "The blue text below is inserted from :" )
   oWord:Selection:InsertBreak( wdLineBreak )
   oSele:typetext( BM_FILE_TXT )
   oWord:Selection:InsertBreak( wdLineBreak )

   // Insert text.
   oSele:TypeParagraph()
   oWord:Selection:Font:Color := rgbBlue
   aLines := bh_FileToArray( BM_FILE_TXT )
   for i := 1 to len( aLines )
      oSele:typetext( aLines[ i ] )
      if i < len( aLines )
         oWord:Selection:InsertBreak( wdLineBreak )
      endif
   endfor
   oWord:Selection:InsertBreak( wdLineBreak )

   oSele:TypeParagraph()
   oWord:Selection:Font:Color := rgbBlack
   oSele:typetext( "End of instertion." )

   oDoc:SaveAs( BM_FILE_WORD )
//   oDoc:Close( .T. )
//   oWord:Quit()
   oWord := nil
   return

procedure CreateTestTxtFile( cFile )
   local cLine := ""
   if file( cFile )
      return
   endif
   cLine += "This is the first line." + hb_eol()
   cLine += "Read at : https://en.wikipedia.org/wiki/History_of_Microsoft_Word" + hb_eol()
   cLine += "The first version of Microsoft Word was developed by Charles Simonyi and Richard Brodie, former Xerox programmers hired by Bill Gates and Paul Allen in 1981." + hb_eol()
   cLine += "This is the last line."
   hb_memowrit( cFile, cLine )
   return

// Transform a file to array ( compile with -lhbmisc ).
function bh_FileToArray( cFile )
   local aArray := {}
   local cLine
   if .not. file( cFile )
      return aArray
   endif
   cLine := hb_memoread( cFile )  // For unix end of line.
   if hb_at( chr( 10 ), cLine ) > 0 .and. hb_at( chr( 13 ), cLine ) == 0
      cLine := strtran( cLine, chr( 10 ), chr( 13 ) + chr( 10 ) )
      hb_memowrit( cFile, cLine )
   endif
   cLine := nil
   hb_fuse( cFile )
   do while .not. hb_feof()
      aadd( aArray, hb_freadln() )
      hb_fskip()
   enddo
   hb_fuse()
   return aArray
// End code.

Francesco Cersosimo

unread,
May 25, 2023, 9:42:21 AM5/25/23
to Harbour Users

Excellent Bernard you are DIVINE.

I have never found so much availability and collaboration.

Thank you forever for your admirable courtesy

Franco Harbour Amateur

Bernard Mouille

unread,
May 27, 2023, 3:35:59 AM5/27/23
to Harbour Users
Hello Francesco,
A code to instert text from dbf table below my signature.
Regards,
Bernard.

// begin code.
/*
   MW_InsertTextFromDbf.prg
   Sample to instert text from dbf table with MS Word file.

   Using HB32, Windows10, MS Word 2007.

   Compile with -lhbwin

   This code is a basic sample for tests.

   Copy the constants files from my web site.

   web : http://bernard.mouille.free.fr/mso-hb32/MW_InsertTextFromDbf.txt
   Last change : 2023-05-27
*/

// Parameter.
#define BM_TABLE_DBF hb_dirbase() + "_Result_Table.dbf"        // File to put in the word document.

#define BM_FILE_WORD hb_dirbase() + "_Result_Word.docx"        // File to create with his path.

#include "mw_WordConstants.h"    // http://bernard.mouille.free.fr/mso-hb32/mw_WordConstants.h
#include "bh_rgbColors.h"        // http://bernard.mouille.free.fr/mso-hb32/bh_rgbColors.h

procedure Main
   local c              // Column num.
   local l              // Row num.

   local i              // Count number.
   local oWord          // Word object.
   local oDoc           // Document object.
   local oSele          // Selection object.
   local oTable         // Table object.
   local aTypes         // Fields type array.
   local xValue         // Table dbf record value.
   local nFields        // Number of fields.


   setmode( 25, 80 )
   setcolor( "GR+/B" )
   @ 0, 0, maxrow(), maxcol() box space( 9 )
   ? "Sample to instert text from dbf table with MS Word file."
   ferase( BM_FILE_WORD )

   CreateTestTable4( BM_TABLE_DBF )


   oWord         := win_olecreateobject( "Word.Application" )
   oWord:Visible := .T.
   oDoc          := oWord:documents:add()
   oWord:ActiveDocument:Select()
   oSele := oWord:Selection

   oDoc:Sections( 1 ):Footers( wdHeaderFooterPrimary ):PageNumbers:Add()
   oDoc:PageSetup:LeftMargin   := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:RightMargin  := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:TopMargin    := oWord:Application:CentimetersToPoints( 1 )
   oDoc:PageSetup:BottomMargin := oWord:Application:CentimetersToPoints( 1 )
//   oDoc:PageSetup:Orientation  := wdOrientPortrait
   oDoc:PageSetup:Orientation  := wdOrientLandscape

   oSele:InsertBreak( wdLineBreak )
   oSele:Font:Bold  := .F.
   oSele:Font:Size  := 36
   oSele:Font:Color := rgbBlue
   oSele:ParagraphFormat:Alignment := wdAlignParagraphCenter
   oSele:typetext( "Sample to put datas from a" )
   oSele:InsertBreak( wdLineBreak )
   oSele:typetext( "dbf table in a MS Word document." )
   oSele:InsertBreak( wdLineBreak )

   oSele:TypeParagraph()
   oSele:Font:Bold  := .F.
   oSele:Font:Size  := 11
   oSele:Font:Color := rgbBlack
   oSele:ParagraphFormat:Alignment := wdAlignParagraphLeft
   oSele:typetext( "Date : " + hb_ttoc( hb_datetime() ) )
   oSele:TypeParagraph()
   oSele:typetext( "Table dbf : " + BM_TABLE_DBF )
   oSele:TypeParagraph()
   oSele:typetext( "Word docx : " + BM_FILE_WORD )
   oSele:InsertBreak( wdLineBreak )
   oSele:InsertBreak( wdLineBreak )
   oSele:typetext( "Insertion of the table." )
   oSele:InsertBreak( wdLineBreak )

   // Insert the dbf table.
   dbSelectArea( 1 )
   dbUseArea( .F., "DBFNTX", BM_TABLE_DBF, "F001", .F., .F. )
   nFields := F001->( FCount() )
   aTypes  := Array( nFields )
   F001->( AFields( , aTypes ) )

   // https://learn.microsoft.com/en-us/office/vba/api/word.tables
   oSele:TypeParagraph()
   oTable := oDoc:Tables:Add( ;
                              oSele:Range ;                        // Range.
                            , F001->( RecCount() ) + 1 ;           // NumRows ( Headers include ).
                            , nFields ;                            // NumColumns.
                            , wdWord9TableBehavior ;               // DefaultTableBehavior ( Enables AutoFit ).
                            , wdAutoFitFixed ;                     // AutoFitBehavior.
                            )
   oTable:Rows:Alignment := wdCenter

   // Align some cells.
   for l := 1 to F001->( RecCount() ) + 1
      for c := 1 to len( aTypes )
         do case
         case aTypes[ c ] == "D"
            oTable:Cell( l, c ):Range:ParagraphFormat:Alignment := wdAlignParagraphCenter
         case aTypes[ c ] == "N"
            oTable:Cell( l, c ):Range:ParagraphFormat:Alignment := wdAlignParagraphRight
         endcase
      endfor
   endfor

   // Give the headers to the tables.
   l := 1 ; c := 0
   c++ ; oTable:Cell( l, c ):Range:Text := "company"        // Compagnie.
   c++ ; oTable:Cell( l, c ):Range:Text := "headquarters"   // Fonction
   c++ ; oTable:Cell( l, c ):Range:Text := "address"        // Adresse.
   c++ ; oTable:Cell( l, c ):Range:Text := "date"
   c++ ; oTable:Cell( l, c ):Range:Text := "amount"         // Compte.
   for i := 1 to c
      oTable:Cell(  l, i ):Range:Font:Bold := .T.
      oTable:Cell(  l, i ):Range:Shading:BackgroundPatternColor := rgbYellow
   endfor

   // Give the datas.
   do while .not. F001->( eof() )
      l++
      for c := 1 to nFields
         xValue := F001->( FieldGet( c ) )
         // Look for the others types.
         if aTypes[ c ] == "C"    // Characters.
            xValue := trim( xValue )
         endif
         oTable:Cell( l, c ):Range:Text := xValue
      endfor
      F001->( dbskip() )
   enddo
   F001->( dbCloseArea() )

   // Set the columns width.
   oTable:Columns( 1 ):Width := 150
   oTable:Columns( 2 ):Width := 150
   oTable:Columns( 3 ):Width := 200
   oTable:Columns( 4 ):Width :=  80
   oTable:Columns( 5 ):Width :=  50

   // Quit the table.
   // https://learn.microsoft.com/fr-fr/office/vba/api/word.selection.endkey
   oWord:Selection:EndKey( wdStory, wdMove )
   oSele := oWord:Selection

   oSele:TypeParagraph()
   oSele:typetext( "End of insertion of the table." )


   oDoc:SaveAs( BM_FILE_WORD )
//   oDoc:Close( .T. )
//   oWord:Quit()
   oWord := nil
   return

procedure CreateTestTable4( cTableName )
   local aDbf := {}
   if file( cTableName )
      return
   endif
   aadd( aDbf, { "company"  , "C",  32, 0 } )
   aadd( aDbf, { "headquart", "C",  24, 0 } )
   aadd( aDbf, { "address"  , "C",  48, 0 } )
   aadd( aDbf, { "date"     , "D",   8, 0 } )
   aadd( aDbf, { "amount"   , "N",   5, 0 } )
   dbSelectArea( 1 )
   dbCreate( cTableName, aDbf, "DBFNTX", .F., "F001" )
   F001->( dbAppend() )
   F001->company      := "Danube Securite Electronique"
   F001->headquart    := "Electronic security"
   F001->address      := "Avenue des Lauriers, FR 83990 St Tropez"
   F001->date         := date() - 100
   F001->amount       := 357
   F001->( dbAppend() )
   F001->company      := "Company Two"
   F001->headquart    := "Nothing"
   F001->address      := "In the cloud, US NY"
   F001->date         := date() - 50
   F001->amount       := 9856
   F001->( dbCloseArea() )
   return
// End code.

Francesco Cersosimo

unread,
May 27, 2023, 6:51:01 AM5/27/23
to Harbour Users

Hello Bernard, SUPERB, I have no way to thank you.

Write the code in an excellent and understandable way for an amateur like me.

Endless thanks.

Franco Harbour amateur

Bernard Mouille

unread,
May 28, 2023, 1:08:44 AM5/28/23
to Harbour Users
Hello Franceco,

A code to look what text is in the Word file.

Regards,
Bernard.

// Begin code.
/*
   MW_ExtractTextSentences.prg
   Sample to extract text from sentences of a Word file.

   Using HB32, Windows10, MS Word 2007.

   Compile with -lhbwin

   This code is a basic sample for tests.

   Copy the constants files from my web site.



#define BM_FILE_WORD hb_dirbase() + "_Result_Word.docx"  // File to create with his path.

#include "mw_WordConstants.h"             // http://bernard.mouille.free.fr/mso-hb32/mw_WordConstants.h

procedure Main

   local oWord            // Word object.
   local oDoc             // Document to extract images.
   local oSents           // Document to put sentences.

   local oSele            // Selection object.
   local Word_File        // File to extract images.
   local oSentence        // Sentence object to extract.
   local i := 0           // Numeric count.
   local xTmp             // Tempory variable.


   setmode( 25, 80 )
   setcolor( "GR+/B" )
   @ 0, 0, maxrow(), maxcol() box space( 9 )

   ? "Sample to extract text from sentences of a Word file."

   ferase( BM_FILE_WORD )

   Word_File := win_GetOpenFileName( , "Select a Word file",,, { "Word files ; *.docx" } )
   if .not. file( Word_File )
      wapi_MessageBox( 0, "Word file not found, abort." )
      return
   endif
   oWord         := Win_OleCreateObject( "Word.Application" )
   oWord:Visible := .T.
   oDoc          := oWord:documents:open( Word_File,, .T. )  // Read only open.

   // Select the document to write text.
   oSents := oWord:Documents:Add()
   oSents:Select()
   oSele := oWord:Selection

   // Option : Page number at the end of page.
   oSents:Sections( 1 ):Footers( wdHeaderFooterPrimary ):PageNumbers:Add()

   // Option : Margins.
   oSents:PageSetup:LeftMargin   := oWord:Application:CentimetersToPoints( 1 )
   oSents:PageSetup:RightMargin  := oWord:Application:CentimetersToPoints( 1 )
   oSents:PageSetup:TopMargin    := oWord:Application:CentimetersToPoints( 1 )
   oSents:PageSetup:BottomMargin := oWord:Application:CentimetersToPoints( 1 )

   oSele:Font:Bold  := .T.
   oSele:Font:Size  := 18
   oSele:typetext( "Extrat all sentences of a Word file." )

   oSele:InsertBreak( wdLineBreak )

   oSele:TypeParagraph()
   oSele:Font:Bold  := .F.
   oSele:Font:Size  := 11
   oSele:typetext( "File " + Word_File )
   oSele:InsertBreak( wdLineBreak )

   oSele:typetext( "Date " + hb_ttoc( hb_datetime() ) )
   oSele:InsertBreak( wdLineBreak )
   oSele:typetext( "Number of sentences " + hb_ntos( oDoc:Sentences:Count ) )

   // https://learn.microsoft.com/en-us/office/vba/api/Word.sentences
   if oDoc:Sentences:Count > 0
      // oSentence doc : https://learn.microsoft.com/en-us/office/vba/api/word.range
      for each oSentence in oDoc:Sentences
         i++
         oSele:TypeParagraph()
         oSele:Font:Bold  := .T.
         oSele:typetext( "Sentence number : " + hb_ntos( i ) )
         oSele:typetext( ", wdActiveEndAdjustedPageNumber : " + hb_ntos( oSentence:information( wdActiveEndAdjustedPageNumber ) ) )
         oSele:InsertBreak( wdLineBreak )
         oSele:typetext(   "wdVerticalPositionRelativeToPage : "   + hb_ntos( oSentence:information( wdVerticalPositionRelativeToPage   ) ) )
         oSele:typetext( ", wdHorizontalPositionRelativeToPage : " + hb_ntos( oSentence:information( wdHorizontalPositionRelativeToPage ) ) )

         xTmp := oSentence:information( wdWithInTable )
         if xTmp
            oSele:InsertBreak( wdLineBreak )
            oSele:typetext( "This sentence is a table element" )
         endif


         oSele:TypeParagraph()
         oSele:Font:Bold  := .F.
         oSele:typetext( oSentence:Text )
      endfor
   endif

   oDoc:Close( wdDoNotSaveChanges )
   oSents:SaveAs( BM_FILE_WORD )
   oWord := nil

   return
// End code.

Francesco Cersosimo

unread,
May 28, 2023, 5:06:35 AM5/28/23
to Harbour Users

Hello Bernard, the code you are illustrating me is a complete manual of VBA (which I don't know) for Harbour. I admire your skill and I am Completely ecstatic, I'm over the moon, for all the help you're giving me.  A thousand thanks are nothing compared to your valuable contribution. Obliged for life. Greetings. Franco Harbour amateur.

Bernard Mouille

unread,
May 28, 2023, 9:09:49 AM5/28/23
to Harbour Users
Hello Francisco,
Thanks for your comment.
Happy to help you.
If you want other way, ask, maybe I have something in my codes.
Regards,
Bernard.

Bernard Mouille

unread,
May 30, 2023, 9:53:31 AM5/30/23
to Harbour Users
Hello Francesco,
A code to find / replace strings in a Word document.
Regards,
Bernard.

// Begin code.
/*
   MW_FindReplace.prg
   Sample to find and replace text with MS Word file.

   Using HB32, Windows10, MS Word 2007.

   Compile with -lhbwin

   This code is a basic sample for tests.

   Change the language ( wdEnglishUS ) if youe text is not english USA.

   Copy the constants files from my web site.

   web : http://bernard.mouille.free.fr/mso-hb32/MW_FindReplace.txt
   Last change : 2023-05-30
*/

// Parameter.
#define BM_FILE_WORD_TEST hb_dirbase() + "_Result_Word_Test.docx"        // Word file to text with his path.

#define BM_FILE_WORD      hb_dirbase() + "_Result_Word.docx"        // File to create with his path.

#include "mw_WordConstants.h"    // http://bernard.mouille.free.fr/mso-hb32/mw_WordConstants.h
#include "bh_rgbColors.h"        // http://bernard.mouille.free.fr/mso-hb32/bh_rgbColors.h

procedure Main

//   local oVB


   local oWord          // Word object.
   local oDoc           // Document object.
   local oSentence      // Sentence object to find.
   local oFind          // Range found object.
   local lReplace       // .T. if a sentence text is replaced.
   local i := 0         // Sentence index.


   setmode( 25, 80 )
   setcolor( "GR+/B" )
   @ 0, 0, maxrow(), maxcol() box space( 9 )
   ? "Sample to find and replace text with MS Word file."
   ?
   ferase( BM_FILE_WORD )
   CreateWordFileTest1( BM_FILE_WORD_TEST )
   hb_fcopy( BM_FILE_WORD_TEST, BM_FILE_WORD )


   oWord         := Win_OleCreateObject( "Word.Application" )
   oWord:Visible := .T.
   oDoc          := oWord:documents:open( BM_FILE_WORD )


   for each oSentence in oDoc:Sentences
      i++
      oFind := oSentence:Find
      oFind:ClearFormatting()
      oFind:Replacement:ClearFormatting()
      oFind:Replacement:LanguageID := wdEnglishUS

      // https://learn.microsoft.com/en-us/office/vba/api/word.find.execute
      lReplace := oFind:Execute( ;
                                 "word test file" ;       //  1 FindText.
                               , .F. ;                    //  2 MatchCase.
                               , .F. ;                    //  3 MatchWholeWord.
                               ,  ;                       //  4 MatchWildcards.
                               ,  ;                       //  5 MatchSoundsLike.
                               ,  ;                       //  6 MatchAllWordForms.
                               , .T. ;                    //  7 Forward.
                               , wdFindStop ;             //  8 Wrap.
                               ,  ;                       //  9 Format.
                               , "replaced words file" ;  // 10 ReplaceWith.
                               )
/* other options.
                               ,  ;                       // 11 MatchKashida.
                               ,  ;                       // 12 MatchDiacritics.
                               ,  ;                       // 13 MatchAlefHamza.
                               ,  ;                       // 14 MatchControl.
                               )
* Not in Word 2007.
                               ,  ;                       // 15 MatchPrefix.
                               ,  ;                       // 16 MatchSuffix.
                               ,  ;                       // 17 MatchPhrase.
                               ,  ;                       // 18 IgnoreSpace.
                               ,  ;                       // 19 IgnorePunct.
                               )
*/
      if lReplace
         ? "Replaced in sentence ", i
         ? "Page                 ", oSentence:information( wdActiveEndAdjustedPageNumber )
         ? "Vertical position    ", oSentence:information( wdVerticalPositionRelativeToPage )
         ? "Horizontal position  ", oSentence:information( wdHorizontalPositionRelativeToPage )
         ?
      endif
   endfor


   for each oSentence in oDoc:Sentences
      oFind := oSentence:Find
      oFind:ClearFormatting()
      oFind:Replacement:ClearFormatting()
      oFind:Replacement:LanguageID = wdEnglishUS

      lReplace := oFind:Execute( "The sun shine" ;        //  1 FindText.
                               ,,,,,,  ;
                               , wdFindStop ;             //  8 Wrap.
                               ,  ;
                               , "The sun shine, the flowers arent beautifull and my tailor is rich" ; // 10 ReplaceWith.
                               )
      if lReplace
         ? "Replaced in sentence ", i
         ? "Page                 ", oSentence:information( wdActiveEndAdjustedPageNumber )
         ? "Vertical position    ", oSentence:information( wdVerticalPositionRelativeToPage )
         ? "Horizontal position  ", oSentence:information( wdHorizontalPositionRelativeToPage )
         ?
      endif
   endfor

   oDoc:Save()
   oWord := nil
   ?
   wait
   return

procedure CreateWordFileTest1( cFile )

   local oWord          // Word object.
   local oDoc           // Document object.

   local oSele          // Selection object.
   if file( cFile )
      return
   endif
   oWord         := win_olecreateobject( "Word.Application" )
   oWord:Visible := .T.
   oDoc          := oWord:documents:add()
   oWord:ActiveDocument:Select()
   oSele := oWord:Selection

   oSele:Font:Bold  := .F.
   oSele:Font:Size  := 36
   oSele:Font:Color := rgbBlue
   oSele:ParagraphFormat:Alignment := wdAlignParagraphCenter
   oSele:typetext( "This is a Word test file" )

   oSele:InsertBreak( wdLineBreak )
   oSele:TypeParagraph()
   oSele:Font:Bold  := .F.
   oSele:Font:Size  := 11
   oSele:Font:Color := rgbBlack
   oSele:ParagraphFormat:Alignment := wdAlignParagraphLeft
   oSele:typetext( "The sun shine." )
   oDoc:SaveAs( cFile )
   oDoc:Close( .F. )
   oWord:Quit()
   oWord := nil
   return
// End code.

Francesco Cersosimo

unread,
May 31, 2023, 4:54:50 PM5/31/23
to Harbour Users

Thank you Bernard, Wonderful.

Franco Harbour dilettante 

Reply all
Reply to author
Forward
0 new messages