MS-Word from PB with COM Interface

Share your advanced PureBasic knowledge/code with the community.
Justin
Addict
Addict
Posts: 832
Joined: Sat Apr 26, 2003 2:49 pm

Re: MS-Word from PB with COM Interface

Post by Justin »

Interacting with word this way it's difficult if you are not familiar with COM, the best way is to try to translate from VBS.
For example this simple VBS code:

Code: Select all

Sub InsertTextAtEndOfDocument() 
 ActiveDocument.Content.InsertAfter Text:=" The end." 
End Sub
Translate into this, creating and saving a new doc.
You will need write access rights to the destination folder,

Code: Select all

Procedure test1()
	Protected._Document doc
	Protected.Range content
	Protected.VARIANT fn, none
	Protected.l hr
	Protected.s file
	
	OleInitialize_(0)
	
	If CoCreateInstance_(?CLSID_Document, 0, #CLSCTX_LOCAL_SERVER, ?IID__Document, @doc) <> #S_OK
		MessageRequester("Error:", "Couldn't create document")
		End
	EndIf
	
	none\vt = #VT_ERROR
	none\scode = #DISP_E_PARAMNOTFOUND
	
	file = "C:\Users\Public\Documents\test2.docx"
	fn\vt = #VT_BSTR
	fn\bstrVal = SysAllocString_(file)
	
	doc\get_Content(@content)
	If content
		content\InsertAfter("Hello World!")
		content\Release()
	EndIf
	
	hr = doc\SaveAs(@fn, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none, @none)
	If hr <> #S_OK
		MessageRequester("Error", "File " + file + " could not be creted")
	EndIf 
	
	SysFreeString_(fn\bstrVal)
	doc\Release()

	OleUninitialize_()
EndProcedure

test1()
Some VBS examples:
https://learn.microsoft.com/en-us/offic ... a-document
Jens-Arne
New User
New User
Posts: 3
Joined: Sun Feb 04, 2024 11:09 am

Re: MS-Word from PB with COM Interface

Post by Jens-Arne »

Thank you very much again! OMG, I'm sure I'm not able to understand how that works...
Post Reply