Quantcast
Channel: Word for Developers forum
Viewing all 4350 articles
Browse latest View live

Word PickerDialog vs Outlook SelectNamesDialog - Word Address Book

$
0
0

I'm developing a VSTO Word Addin, and I'm tring to open a 'Global Adress List' in the MS Word (see bottom image).

Programatically I thought I could use the PickerDialog unfortunately i'm unable to open such a window. 

The only way, I managed to open was using the Outlook Application:

            ////////////////////////
            Outlook.Recipient theUser;
            Outlook.Application OLApp = (Outlook.Application) Helper.CreateObject("Outlook.Application"); //new Outlook.Application();// 
            if (OLApp.ActiveWindow() != null) //only if there's a window
                OLApp.ActiveWindow().Activate();  //make sure outlook comes to foreground first
            else
            {
                // These 3 lines solved the problem
                Outlook.NameSpace ns = OLApp.GetNamespace("MAPI");
                Outlook.MAPIFolder f = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                System.Threading.Thread.Sleep(5000); // test 
            }

            Outlook.SelectNamesDialog OLDialog = OLApp.Session.GetSelectNamesDialog();
            OLDialog.SetDefaultDisplayMode(Outlook.OlDefaultSelectNamesDisplayMode.olDefaultSingleName);
            
            if (OLDialog.Display())
            {                
                if (OLDialog.Recipients.Count > 0)
                {
                    theUser = OLDialog.Recipients[1];
                    string name = theUser.Name;
                    string email = theUser.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
                    AddFormatedEmailTo(name, email);

                }
            }            

This off course open an Outlook instance, and finally the Address Book Window.

Anybody knows any way to do this without using the Outlook.Application ?

Something like:

//http://social.msdn.microsoft.com/Forums/office/en-US/9b753040-72e2-4e11-bf31-63e1bd73e20c/pickerdialog-in-word-how-can-i-use-it-in-a-c-addin
            Microsoft.Office.Core.PickerDialog pd = ThisApplication.PickerDialog;
            pd.DataHandlerId = "{00020404-0000-0000-C000-000000000046}"; //HKEY_CLASSES_ROOT\MsoPeopleDataHandler.PeopleDataHandler\CLSID
            pd.Title = "Sample Picker Dialog";            
            pd.Show();

I appreciate your help.

Best Regards


Improve on Mail Merge Code

$
0
0

Hello all,

I am working on a mail merge code where the main document structure would always be the same but the Source Data would constantly be changing. In that regard I want a code that would insert the merge field and change the Data Source on the code. The recorded code with only comment added to it is as follows:


  1. Sub Macro3()

    'This prgram should print to pdf copies of mail merge document.

        'Start the MailMerge process
        ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument
        ActiveDocument.MailMerge.MainDocumentType = wdFormLetters

        'Connection to the Data Dource
        ActiveDocument.MailMerge.OpenDataSource Name:= _
            "C:\Users\UserName\Desktop\FileName.xlsx", _
            ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
            AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
            WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
            Format:=wdOpenFormatAuto, Connection:= _
            "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\Users\UserName\Desktop\FileName.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=35;Jet O" _
            , SQLStatement:="SELECT * FROM `NamedRangeInExcel`", SQLStatement1:="", SubType:= _
            wdMergeSubTypeAccess

        'Move to the first merge field position
        Selection.MoveRight Unit:=wdCharacter, Count:=20
        Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend

        'Insert the first merge field
        ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:= _
            "Sample_"

        'Move to the second merge field position
        Selection.MoveDown Unit:=wdLine, Count:=2
        Selection.MoveLeft Unit:=wdCharacter, Count:=8
        Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend

        'Insert the Second merge field
        ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:= _
            "REF_"

        'Move to the third merge field position
        Selection.MoveDown Unit:=wdLine, Count:=2
        Selection.MoveLeft Unit:=wdCharacter, Count:=11
        Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend

        'Insert the third merge field
        ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:= _
            "TYPE"

        'Move to the fourth merge field position
        Selection.MoveLeft Unit:=wdCharacter, Count:=35
        Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend

        'Insert the fourth merge field
        ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:="FA_"

        'Move to the fifth merge field position
        Selection.MoveLeft Unit:=wdCharacter, Count:=26
        Selection.MoveRight Unit:=wdCharacter, Count:=1
        Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend

        'Insert the fifth merge field
        ActiveDocument.MailMerge.Fields.Add Range:=Selection.Range, Name:= _
            "Sample_"

        'Print the document to PDF

        With ActiveDocument.MailMerge
            .Destination = wdSendToPrinter
            .SuppressBlankLines = True
            With .DataSource
                .FirstRecord = wdDefaultFirstRecord
                .LastRecord = wdDefaultLastRecord
            End With
            .Execute Pause:=False
        End With
    End Sub
                                                               

I am seeking the following improvements:

to make the Name parameter of the OpenDataSource Method a variable and to make Data Source in the connection parameter also a variable.

Thanks all.

Link to earlier question which I have tried to improve on.


Thanks to all that continue to serve as help HashMan




Word 2013 Automation Pops Behind calling application

$
0
0

Starting with Word 2013 when I run the simple code below the Word window shows up Behind the calling application.  Previously Word would show up in front.  This was tested on Windows 8 with Word 2010 and Windows 8 with Word 2013.  2010 works just fine, 2013 pops behind.

  Dim wordApp = CType(CreateObject("Word.Application"), Word.Application)

  Dim wordDoc = wordApp.Documents.Open(CType("c:\test\test.docx", Object), 1, 1, 0) ' open for Readonly
  wordApp.Visible = True
  wordDoc.PrintPreview()
  wordApp.Activate()

Thank you.

David

Word-generated tagged PDFs do not have correct structure for paragraphs split across page boundaries

$
0
0

We're post-processing PDFs generated by Office 2007 and up.  With the "Document structure tags for accessibility" option checked, it does a pretty good job of generating a description of the document structure in the PDF structure tree.

However, if a paragraph splits across pages, the structure tree records this as two separate paragraphs with apparently nothing to tie them together.  Using Adobe's Acrobat plug-in for Word (version 9, the latest I have), it makes use of something called a Marked Content Reference to tie the second part of the paragraph to the first (see http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/pdf_reference_archives/PDFReference15_v5.pdf, page 732).

Does anyone know if there is a way (either through the UI or programmatically) to generate the correct PDF tagging for split paragraphs in Word?

Data transfer from MS Project to Word

$
0
0

Greetings,

I have developed a Microsoft Project Add-In.

Now I want to Transfer Information (text, grafic) via my Add-In in MS-Project from MS-Project to Word.

Whatpossibilitiesof programming have I?

Thank you very much!

   Michael

Concatenation of mergefields no longer works in Word 13

$
0
0

John James andJennifer James

If you copy and paste the above into a word document, and do ALT F9 I think you will see the concatenated merge fields which are not working in Word 2013.

I have 4 names which I string together putting commas and "and" in the appropriate place depending if some or all 4 names are present. This works up to 2010 but not in Office 13.

.NET Programatic Open Issue with .DOC

$
0
0

I am having 2 issues with programmatically opening & processing, .doc documents: 
    1.  opening a modified MS Word .doc document from an unmodifed executable. 
    2.  debugging from VS 2010

Issue 1 - programmatically opening .doc documents.

I suppport a .NET Console App that pre-populates a set of Word documents that each contain a protected Form.  The variable information is used to pre-populate roughly 75% of the Form fields.  The resulting documents are then provided to the end users for completion.  The forms contain fields that are idendtified by named BookMarks.  Some have specific length and default text attributes.  Both base documents are essentially processed in the same manner.
Basic process flow:  a request is received to generate a set of pre-populated forms.  The console application retirieves the variable data.  The base document is opened (like a template), and saved as a new document, with a new name.  The document is then unprotected, and the approriate form fields are initialized with the variable text & data.  The documents are then re-protected, saved and emailed to the users.
The .NET console application was created with VS 2010 on a XP dev box, with a target framework of .NET
 2.0 and the "Any CPU" platform.  The documents form fields were defined with MS Word 2007.  The app uses the Microsoft.Office.Interop.Word .dll, Product version 12.0.4518.1014, to process the documents.  The app .exe, associated .dlls and base .doc files are deployed to a dedicated XP machine, which has .NET framworks:  1.1, 2.0, 3.0, and 3.5, as well as Office 2007.  The "Doc Process" app has been running without issue for approximately a year and a half.  One text change was made to one of the document forms in May - no impact to the application.
 A recent text change was made to one of the form fields - default text and length change.  The updated .doc is what is being reported as corrupt.  Reported error is:
System.Runtime.InteropServices.COMException (0x800A141F): Word was unable to read this document.  It may be corrupt.
Try one or more of the following:
* Open and Repair the file.
* Open the file with the Text Recovery converter.
   at Microsoft.Office.Interop.Word.Documents.Add(Object& Template, Object& NewTemplate, Object& DocumentType, Object& Visible)
 
 Opening the document with the "Open and Repair" option showed 8 'Drawing errors'.   After unprotecting the .doc and re-opening with "Open and Repair" seemed to correct the 8 reported errors, however the .NET application still reports the same error.  I am unable to correct this.  The .doc changes were re-applied with MS Word 2007 from both Windows 7 and Windows XP from the original document that can be processed.  Both attempts still result in the same error.
 My assumption is that something has happened in the either the Office implementations - changing the base structure of the document or some simialr enhancement to the .NET Framework.  I have also tried to 'save as' the document as a .rtf and then back to .doc - no change.
 Either way, I'm at a loss as to how to proceed.
 
 Issue 2 - debugging from VS 2010.
 w/in VS 2010.. somewhat of a diff't issue in that the reported error is: 
 
 System.InvalidCastException: Unable to cast COM object of type 'Microsoft.Office.Interop.Word.ApplicationClass' to interface type 'Microsoft.Office.Interop.Word._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00020970-0000-0000-C000-000000000046}' failed due to the following error: Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)).
   at Microsoft.Office.Interop.Word.ApplicationClass.set_Visible(Boolean prop)
 
 Project references to the interop dll  have been tried to the original .dll (comon directory) as well as to c:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Word.dll.  Resulting error message is the same.   With either referernce - compiles are successful.   Current target is the 2.0 .NET framework with 'x86 CPU'.
 
 Don't know why it's considered an intreface or how to 'register' the PIA (came w/ VS 2010)
 Any suggestions and help is greatly appreciated!

 Interop Info:
 Runtime Version:  v1.1.4322  (pulled via VS 2010 properties)
 
  Property Value
 Description Description
 File description Microsoft.Office.Interop.Word
 Type Application extension
 File version 12.0.4518.1014
 Product name 2007 Microsoft Office system
 Product version 12.0.4518.1014
 Copyright © 2006 Microsoft Corporation.  All rights ...
 Size 762 KB
 Date modified  1/ 18/ 2011   5:27 PM
 Language Language Neutral
 Original filename Word Primary Interop Assembly


Style problem

$
0
0

We have a template with a style called "Paragraph". The following code applies that style to the selected pragraph in any document which uses that template.

Selection.Style = ActiveDocument.Styles("Paragraph")

We have a TEX file opened using tex2word. (Very succesfully). We apply our template to that file using

  With ActiveDocument
    .UpdateStylesOnOpen = True
    .AttachedTemplate = mytemplate
  End With

However when you do

Selection.Style = ActiveDocument.Styles("Paragraph")

A style called "Heading4,Paragraph" is applied and the stlye "Paragraph" cannot be found in the document.

1. Why has the style "Paragraph" disappeared.

2. Why does "Selection.Style = ActiveDocument.Styles("Paragraph") " not give an error?

We have tried renaming "Heading4,Paragraph" to "Paragraph" but when you click on OK the new name reverts to "Heading4,Paragraph"

Any suggestions?


How can I set Word field codes programmatically

$
0
0

I'm developing an application in Microsoft Dynamics AX and I need to create a Word document programmatically.

The document will be printed double sided but, apart from the last page, the even pages will be blank. Therefore I only need to number the odd pages,  In other words I need to amend the normal "Page X of Y" so that it prints "1 of n" on the first page, "2 of n" on the third page, "3 of n" on the fifth page etc.

The field code that I need to set is: Page {= {={ PAGE } + 1 } / 2} of { = { NUMPAGES } / 2 } but I can't find a way of doing this in program code.  The curly braces in the UI seem to translate to ascii codes 19 and 21 but if I try to update the Text property on the Field.Code range, it doesn't work.

Any ideas would be gratefully received.  I'm coding in X++ but examples in any language will be fine!

Run-time error 5941 "The requested member of the collection does not exist"

$
0
0

OKAY... I thought I understood how Watermarks worked, but heres the story.

There are several missives regarding this issue, mine is similar, but different.  In a protected file which is Read-Only, I want to create a macro that when run, unlocks the password protected document, inserts a "Draft 1" watermark on the header/footer page, then locks back down.  This is being run on Word 2010, System 7  to all users. 

I noticed when reviewing the code, the 'path' includes my employee number in the path.  It did not do this in 2003 on XP.  I thought by changing this to: %username% in the path, the code would work on any computer it was opened on. 

First, I ran a macro, recording all the steps to insert the watermark.  Then I edited the code in the editor.  When running the macro, the file does not unlock the file, but rather, inserts a watermark behind the text layer.  It is not placing the watermark on the header/footer as it did when I first recorded the macro, therefore, I cannot select Page Layout-Watermark-Remove Watermark.  If I change my id number in the code to: %username%, it gives me the run-time error 5941 and produces nothing.  Where is this going wrong?  When I debug the code, nothing comes up

If ActiveDocument.ProtectionType <> wdNoProtection Then
    ActiveDocument.Unprotect Password:="password"
    Application.Templates( _
        "C:\Users\emp_no or %username%\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("DRAFT 1").Insert Where:=Selection.Range, RichText _
        :=True
    ActiveDocument.Protect wdAllowOnlyReading, False, Password:="passsword"

End If

End Sub

What is the bitmap resolution for ribbon elements on a tablet?

$
0
0

Hi;

We have our AddIn running on a tablet (didn't have to do anything - it just installed and ran).

But the bitmaps in the ribbon look poor. We figure it has a better resolution than the 16x16 and 32x32 of a PC. Is there a set resolution for small and large on a tablet? And what should we query in the O/S to know if we should use the better resolution?

thanks - dave


Who will win The Windward International Collegiate Programming Championships?

How to set Outline Number in word with C#?

$
0
0

Hi,

I merge some word documents into new document. And I need set outline number for imported document in new document.

How to I do?


 


Roy Wang



possible bug in Word.ContentControl?

$
0
0

it seems to be the Word.ContentControl does something wrong.
the method SetPlaceholderText is not ready to use in a latebind scenario.
it works well with a method pointer/delegate(early bind)
i use c# but anyway, try visual basic

Dim control as Word.Control = GetControlAnywhere()
control.SetPlaceholderText(Nothing, Nothing, "text")

works as well but now change control to Object. the vb auto-dispatch feature does a good job normaly but you got a TypeMissmatchException. it doesnt works also with c# dynamics or GetType().Invoke...
tested on different machines/vm's.

not sure but the IDispatch::Invoke implementation is the problem at the end?
i do a test in c++ and a direct Invoke call with the same result.




Steps to Create Add-in in Word 2010 using VBA

$
0
0

Hello all,

I have the following code that I want to run as add-in. Can you please give me the steps to create add-in in MS Word 2010. Thanks in advance.

Sub MergeDataSource()


     Dim fd As FileDialog
    Dim xfilepath As Variant
    
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    Set myMerge = ThisDocument.MailMerge
    
    'Dim doc As Word.Document
    
    myMerge.MainDocumentType = wdNotAMergeDocument
    myMerge.MainDocumentType = wdFormLetters
    
    'Browse for the Datasource
    
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    ' Set the title of the dialog box.
    
    With fd
    
    .Title = "Select the Excel File"
        If .Show = True Then
         ' Assign the file to a variable xfilepath.
            xfilepath = fd.SelectedItems.Item(1)
 
            Else
                MsgBox "You clicked Canncel in the file dialog box.", , "Cancelling Merging process"
                Exit Sub
      End If
    End With
    
    
    'Connection to the Data Dource
    On Error Resume Next
    myMerge.OpenDataSource Name:= _
        xfilepath _
        , ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
        AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", _
        WritePasswordDocument:="", WritePasswordTemplate:="", Revert:=False, _
        Format:=wdOpenFormatAuto, Connection:= _
        "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=xfilepath;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";J" _
        , SQLStatement:="SELECT * FROM `HASHMAN19`", SQLStatement1:="", SubType:=wdMergeSubTypeAccess
    
     On Error GoTo 0
    'Print the document to the default printer
    
    With myMerge
        .Destination = wdSendToPrinter
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With
End Sub

Thanks all.


Thanks to all that continue to serve as help HashMan


Page footer

$
0
0

How do I get 'Page n of n' in the page footer?

Right now it displays 'Page 1 of 1' on every page.

I right-clicked in the footer and chose 'Edit footer' but what now, there is no help and I have no idea what to do as the menus have no option to insert special values. I used to know how to do this with Word 2003 but with Word 2010, I'm completely lost as everything had changed.

Please don't tell me this is the wrong forum as I have no idea how to find the right forum.

Sample VBS code for Watermark on Word

$
0
0

Hello!

Can anybody help me with a visual basic script code for generating a new word document, write some text and print a watermark "NON CONTROLLED COPY". I've looked all around and I haven't found any. I need to generate a .vbs file for this action.

If this kind of question must not be here, please redirect.

Thank you!

Adding a text in MS Word using Visual Basic 6.0

$
0
0
How can I add a text in an existing MS Word Document without replacing the current text using VB 6.0?cing the current text using VB 6.0?

Error "Error loading type library/DLL" when trying to access COM add-ins in Word

$
0
0

Hi 

This error "Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))" was raised when trying to open a document in Word 2010 using a Word add-in. An empty Word window was loaded but the document was not. 

The error only happens in one machine (OS: Windows 7, Office 2010). Tried reinstalling Office 2010 on this machine but it does not work.

Here are the code snippets with the exception details: 

Private ThisWordApp As Microsoft.Office.Interop.Word.Application = Nothing
Private IWord As IAddinUtilities = Nothing

Public Sub LaunchMSWord()
	Try
		Try
			ThisWordApp = TryCast(GetObject(, "Word.Application"), Microsoft.Office.Interop.Word.Application)	 ' Error raised at this line
		Catch ex As Exception
			' EXCEPTION DETAILS
			' ex.Message = Cannot create ActiveX component.
			ThisWordApp = New Microsoft.Office.Interop.Word.Application
		End Try


		If TypeName(ThisWordApp) = "Nothing" Then			' This is False
			ThisWordApp = New Microsoft.Office.Interop.Word.Application		' Skipped
		End If

		ThisWordApp.Visible = True

		For Each addIn As Microsoft.Office.Core.COMAddIn In ThisWordApp.COMAddIns 	' Error raised at this line
			If addIn.Description = "Office Word AddIn" OrElse addIn.ProgId = "Office.Word" OrElse _
			addIn.Description = "Office Word AddIn  -- an addin created with VSTO technology" Then
				IWord = addIn.Object
				Exit For
			End If
		Next

	Catch ex As System.Runtime.InteropServices.COMException
		' EXCEPTION DETAILS 
		' ex.Message = Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY))
		' ex.StackTrace = at(Microsoft.Office.Interop.Word.ApplicationClass.get_COMAddIns())
		'  at Office.Word.LaunchMSWord()
		' ex.Source =  Microsoft.Office.Interop.Word()
		' ex.ErrorCode = -2147312566
		' ex.Data.ToString =	 System.Collections.ListDictionaryInternal()
		Throw ex

	Catch ex As Exception
		Throw ex
	End Try
End Sub

Reference added: Microsoft.Office.Interop.Word (Path:C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Word.dll)

Any idea what else I should check for on that machine? Thanks.


need an arbitrary field code in Word 2007

$
0
0
all,

I am inserting fields manually in a document as placeholders for data being thrown to them through VBA. My question is, which field code can/should I use for this purpose?  Does it really matter?  According to this, it seems as though it does:

http://office.microsoft.com/en-us/word-help/field-codes-in-word-HA010100426.aspx

I can't mail merge the data coming from Excel because I have to create one word document at a time.

Does anyone have ideas on this?  I thinking it really doesn't matter for this purpose...   thanks.

Word 2010 New Document Always in Compatibility Mode

$
0
0

Even the word template is created using word 2010 and save in dotx format , the file created basded on this template is always in compatibility mode. 

Also in Options -> Save -> Save file in this format, the selected value is word 97 - 2003. The issue is if I change it toWord Document (.docx), when I close the word and open it again, the changes doesn't stick.

I found a lot suggestion in Google, and tried changing registry, recreate normal.dotx... nothing works.

Am I missing somthing here? Is it a group policy issue?

Thank you for you help

Andy

Viewing all 4350 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>