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

Can VS2013 Express create an extension application for Microsoft Word?

$
0
0

I want to create a WinForm application that can use the MS Word to print out the details entered.

Is VS2013 Express has the capability to use MS Word?..

So for clarrification here are the details of my plan..

A user can input the details on the application then after they press the Finish Button the application will auto open the MS Word and insert all the details from the application.


How to create conditional text based on value selected in content control

$
0
0

Hi

 

I need to create a Word document with text in a paragraph that changes based on the selection on a drop-down list content control, using Word 2007.

  •  I would like to do this without code, using built-in functions if possible.

For example I create a drop-down list content control containing two options; “You” and “Your client” that is within a sentence.

 

If the user selects the first option, “You”, a paragraph elsewhere in the doc automatically updates to “You will need to attend in person”. If they select “Your client”, it will read “We will send the form to your client”.

 

Nb. The updating paragraph doesn’t just mirror the selected text, it contains different text based on the choice.

 

I have tried referencing the drop-down list using an IF field, I have also wrapped the content control into a bookmark and tried referencing that, but neither work. Very grateful for any help.

Document cannot be saved on PC. TrackRevisions is not available. Threw an exception

$
0
0

Hello all,

I hope someone can help me. I'm working with a Word document in my application and I cannot do a 'saveAs' nor 'publish' the document. The reason is why an exception is thrown in the plugin.

The document is a formulary and it is protected.

When I try to 'save as' I get the exception when I try to do:

revisionsActive = document.TrackRevisions;
because if you see inside the property, it is not available. The exception:

Exception: The method or property TrackRevisions is not available because the document is protected.

StackTrace:   at Microsoft.Office.Interop.Word.DocumentClass.get_TrackRevisions()

HelpLikn: wdmain11.chm#37373

When I try to publish the document I get the exception in the code:

 wordApp.ActiveDocument.AcceptAllRevisions();

the same exception:

This method or property is not available because the document is protected.

I have several documents protected but just two of them threw this exceptions and I cannot save or publish them.

I tried to 'jump' this code and I was following the TrackRevision property. Once I executed:

document.MailMerge.Execute(ref objectTrue);

the TractRevision is available again.

but as I told before, it just happen in two documents. Maybe they have something different but I cannot find it. Any idea, please?
Can this property be not available in some cases? should I modified it or assign its value inside a try catch?

Thank you for your help!


Updating word document from ASP.Net page

$
0
0

I am trying to update word doucment using bookmark from an ASP.Net page.

Development environment has Windows 7 64, Office 2010, Office runtime

using Microsoft.Office.Interop.Word;

               

try
            {
                Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                Document wordDoc = new Document();

                object fileName = "E:\\Employee.docx";
                object readOnly = false;
                object isVisible = true;
                object oMissing = System.Reflection.Missing.Value;

                wordApp.Documents.Open(fileName, ref oMissing, readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                wordDoc.Activate();

                if (wordDoc.Bookmarks.Exists("EmployeeName"))
                {
                    object oBookmark = "EmployeeName";
                    wordDoc.Bookmarks.get_Item(ref oBookmark).Range.Text = "me";
                }


                wordApp.Documents.Save(ref oMissing, ref oMissing);
                wordApp.Application.Quit(ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception expn)
            {
                Response.Write("<br>" + expn.Message);
            }

I am getting error message:

Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

Created folder C:\Windows\SysWOW64\config\systemprofile\Desktop also in System32/config/systemprofile/Desktop and assigned Network Services with appropriate rights

Then, did:

In DCOMCNFG, right click on the My Computer and select properties. 
2. Choose the COM Securities tab
3. In Access Permissions, click "Edit Defaults" and add Network Service to it and give it "Allow local access" permission. Do the same for <Machine_name>\Users.
4. In launch and Activation Permissions, click "Edit Defaults" and add Network Service to it and give it "Local launch" and "Local Activation" permission.

Still having the same issue, any workaround will be appreciated.

Marshal.releasecomobject does not release the object.

$
0
0

Hello,

i am using the following code :

 Dim oword AsObject  oword = CreateObject("word.application")

Dim odoc AsObject

     odoc = oword.documentsdim template as string 'path to templateoword.documents.open(template)

dim source as string 'path to mailmergedatasource

oword.activedocument.mailmerge.opendatasource(source)

'count number of lines in mailmergedatasource

for x as integer = 1 to count_lines

with oword.activedocument.mailmerge.destination = 1 'wdsendToNewdocument

with .datasource

.firstrecord = x

.lastrecord = x

end with

.datasource.activerecord = x

path = oword.ActiveDocument.MailMerge.DataSource.DataFields("dosnumber").Value

 path = pathtoserver& path & "_LTR.doc"

.execute(pause=true)

end with

if oword.ActiveDocument.Saved = FalseThen oword.ActiveDocument.saveas(path)

oword;activedocument.close()next

odoc.close(0)


NAR(odoc)

oword.quit(0)

NAR(oword)

PrivateSubNAR(ByValoAsObject)

Try

While(System.Runtime.InteropServices.Marshal.ReleaseComObject(o)> 0)

EndWhile

Catch

Finally

o = Nothing

EndTry

odoc = nothing

oword = nothing

GC.Collect()

GC.WaitForPendingFinalizers()

GC.Collect()

GC.WaitForPendingFinalizers()

running this code with only 4 letters to do, took after the closing of word still 6 minutes before winword.exe *32 disappeared from the task list.

For what reason is the process winword.exe 32* still running and cannot not be deleted from the tasklist with the command end selected process?

It's making a new mailmerge very slow.

Windows7 64 bit office 2010 32 bit

Any help would be appreciated!

Bert

Control document position in active window

$
0
0

Hi

In one of my customers COM Addins för Word 2010, we have some code running in the DocumentBeforeSave event in order to verify some content in the document. This event is also triggered when Autosave kicks in.

To make sure the document position within the ActiveWindow is not changed in this process, we have used the <document>.ActiveWindows.VerticalPercentScrolled value to get before and reset after our check is done.

This works fairly well with smaller documents, since the value you get is a percentage och the whole document.
But the larger the document get, the less accurate is this approach.
The document can shift half a page up or down, which is not appreciated by the users.Does anyone know of a better way to make the document position remain the same during saves?


Best Regards Peter Karlström Midrange AB, Sweden

Document.Compare IgnoreAllComparisonWarnings - what problems or issues will be ignored?

$
0
0

I am looking to gather more information on what problems, issues, or messages will be ignored when using the Document.Compare IgnoreAllComparisonWarnings set to true.

We are looking into this further because for the following issue: when comparing a document with 'track changes' turned on, you will receive an error message and no comparison occurs.

What are other comparison issues that I may run into if I do not set IgnoreAllComparisonWarnings equal to true.

Thank you,

Tony

Best way to Serialize/Deserialize a word document?

$
0
0

within an office add-in for word what is the best way to serialize/Deserialize a document ?

Currently I'm using WordDocument.SaveAs and Word.Application.Documents.Open to save the document out to a file first and to load from a file but this is quite clunky. is it possible to serialize/deserialize a word document entirely in memory ?

Ideally i'd have a solution that works for versions of word 2007 onwards.

Regards

-John



Moving field values into a text box....

$
0
0

Hi

I am working on documents in Word 2013. Situation is that the first page of each document has document properties that display as fields, for example a document Title and a document Subject.

Due to a new template design I need to move these fields to a new position on the front page. The easiest seems to put these fields in a text box and then position the text box as necessary. I have no real problem positioning a text box, but haven't a clue how to move the fields into the text box.

What I also want is to apply a name to the text box, for example call it SubjectTitle, instead of having some cryptic "Text Box 64" text. Using a system defined name for the text box could cause future problems, there are 500 documents from different users. Any ideas/suggestions on a VB Script that can help me do this would be much appreciated.

Thanks

Robin


Is there a way to check the validity of internal hyperlinks inside an active word document?

$
0
0

Hi All,

I'am trying to build an ms word add-in in which ,

I wanted to check for a particular scenario,i.e say a user inserts a bookmark and later in the document adds a cross reference to this bookmark.But he then deletes the bookmark and forgets to update his document, now upon pressing ctrl+click (to follow the link) takes me to the start of the document, instead I wanted to know if we can display a specific message to the user telling him to update his document or even  remove the cross reference by any chance .

Please let me know how I can go about this ,I know how to test for invalid links with respect to toc. But this scenario is confusing.Any help is much much appreciated.Thanks in advance :) 

String Compare Stumber

$
0
0

I'm stumped with a string compare problem.  The following code should illustrate.  I am trying to detect a change in a RichText type content control.  I want to detect any changes e.g., format etc. and not just a text change.  I've attempted to set a string variable equal to the WordOpenXML string value of the CC range.  I then attempted to run a loop to compare the string variable to the WordOpenXML string.  When they are no longer equal represents a change.

For some reason (and the number 3500 may just be on my PC), the strings match up to the 3500th character and then they no longer match.  Can anyone replicate/explain this weird behavior?

Note:  This is cross posted at VBExpress: 

http://www.vbaexpress.com/forum/showthread.php?51121-String-Compare-Stumper

Option Explicit
Option Compare Text
Sub Test()
  With ActiveDocument
    .Range.Delete
    .Range.InsertBefore vbCr + vbCr
    .ContentControls.Add wdContentControlText, .Paragraphs(1).Range
    .ContentControls.Add wdContentControlRichText, .Paragraphs(2).Range
    .ContentControls(1).Range.Text = "A"
    .ContentControls(2).Range.Text = "A"
    MsgBox CCChange(.ContentControls(1))
    MsgBox CCChange(.ContentControls(2))
    MsgBox CCChange(.ContentControls(2), False)
  End With
End Sub
Function CCChange(oCC As ContentControl, Optional bNormal = True) As Boolean
Dim lngIndex As Long 'For demo/testing only.
Dim strCC_Text As String
  CCChange = False
  Select Case oCC.Type
    Case 1, 3, 4, 5, 8
      strCC_Text = oCC.Range.Text
      Do While strCC_Text = oCC.Range.Text
        DoEvents
        On Error GoTo Err_Object
        lngIndex = lngIndex + 1 'For demo/testing only to trigger a simulated change.
        If strCC_Text <> oCC.Range.Text Or lngIndex = 3 Then
          CCChange = True
          Exit Function
        End If
      Loop
    Case 0, 2
      strCC_Text = vbNullString
      strCC_Text = CStr(oCC.Range.WordOpenXML)
      If Len(strCC_Text) = Len(oCC.Range.WordOpenXML) Then
        MsgBox Len(strCC_Text) & " " & Len(oCC.Range.WordOpenXML) & " They appear to be the same at least by characters count."
      End If
      Select Case True
        Case bNormal
          Do While strCC_Text = oCC.Range.WordOpenXML
            'So why does't this code execute?
            DoEvents
            If strCC_Text <> oCC.Range.WordOpenXML Then
              DoEvents
              CCChange = True
              Exit Function
            End If
          Loop
        Case Else
          'It seems there is a difference with the 3501 character :-(
          Debug.Print Mid(strCC_Text, 3051, 1) & " " & Mid(oCC.Range.WordOpenXML, 3051, 1)
          'Why would that be since the first string is set to = the second string?
          Do While Mid(strCC_Text, 1, 3050) = Mid(oCC.Range.WordOpenXML, 1, 3050)

            DoEvents
            If strCC_Text <> oCC.Range.WordOpenXML Then
              DoEvents
              CCChange = True
              Exit Function
            End If
          Loop
        End Select
  End Select
lbl_Exit:
  DoEvents
  Exit Function
Err_Object:
  Resume lbl_Exit
End Function


Greg Maxey Please visit my website at: http://gregmaxey.mvps.org/word_tips.htm

Formating paragraphs based on the first characters

$
0
0

I have a word file (which I have created from Excel) that includes a code (2 letters and a space) at the start of each paragraph indicating the kind of style I want the paragraph to take on -- all this is successful.

Now I am struggling to create a VBA Macro (for word) that goes through the word file paragraph by paragraph and changes the paragraph style based on the code (first two letters/first word) at the start of the paragraph.

So my word file looks like:

H1 jkhb  lkjn ljbn m ljn

H2 lkj lknj l,nj ,lm jknljn lkn j;kl n;kn m

BL lkjnn lknj l  lblopj I  ljkb l hbl j b

etc.

What I was hoping to create is a Macro that does something like (NOTE this is not my code -- it is my thinking):

Sub format_para()

For each paragraph in selection (note I would ideally like to do this to the text I select and not the whole file)

      If "the first two characters" = "H1" Then

              change the style of the paragraph to "Heading 1"

       ElseIf "the first two characters" = "H2" Then

              change the style of the paragraph to "Heading 2"

       ElseIf "the first two characters" = "BL" Then

              change the style of the paragraph to "BL"

       End If

Next paragraph

Then I'd like to write another loop that replaces all the "H1 ", "H2 ", "BL " with nothing

End Sub

I have really and sincerely searched for clues, but am getting a little stuck -- if anybody can help me I would be so delighted.

Thank you in anticipation

Aarnout

Multiple caret

$
0
0
I would like to be able to show multiple caret positions in a document and possible add a tooltip to each.  Is this possible within an AddIn or even embedding the Word control in an application?

.Net Framework 3.5 using Office PIAs

$
0
0

Our existing VS 2008 Framework 3.5 application is on the Windows 2003 web server. The app is populating Word documents using the .doc templates created in the Office 2003. The generation is happening on the server. There is an interop assemply reference in the code.

This all need to be migrated to the Windows 2008/ 64 bits web server. Would you recommend upgrading/installing the Office 2010 or 2013 to work with framework 3.5 and should we install 32 or 64 bits? The plan is not to upgrade the app framework, only to change the COM object reference. Can we keep the existing .doc templates or will need to convert? The end users (who are the consumers of the generated docs) have Office 2010. Thanks a lot!

Macro For Formating Pictures - add box frame, caption (Figure 1:)

$
0
0

I had a macro in 2003 to do the above and resize but we recently upgraded to office 2010.  I had previously recorded it, which I can't do with word 2010.  Very frustrating.  I have no experience with writing vba macro code and see there are multiple requests for similar type features, that people have kindly supplied.   I wonder if someone could provide the code for me to simply add a box (frame) around a picture that I would have previously selected, plus add a capture above the picture with Figure #:    I don't need it resized now with Word 2010.   I create documents that include a great number of pictures that I reference with the Figure #.  I normally select the pictures and then apply the macro but now I have to manually do this and its really time consuming. 


how to get customer list template ?

$
0
0

Hi guys,

so far i've written a "template.dotx" file which contains a multi-level list template in it.

and i wanna use this list template, so i write the code below :

string exePath = System.Windows.Forms.Application.StartupPath + "\\";
            Word._Application wordApp = new Word.Application();
            Word._Document templateDoc = wordApp.Documents.Open(exePath + "template.dotx");
            templateDoc.Activate();


            Word.ListTemplate lt = wordApp.ListGalleries[Word.WdListGalleryType.wdOutlineNumberGallery].ListTemplates[7];

but it seems the wordApp object doesnt find my list template, for  "wordApp.ListGalleries[Word.WdListGalleryType.wdOutlineNumberGallery].ListTemplates" only have 7 default template?

but if i open the dotx with office2013, it contains the list template i've created.

is there anyway i can obtain the template?

Ribbon/dynamicMenu: imageMso is not visible when a dynamicMenu is set to enabled="false"

$
0
0

Hi

When a button in my Word Ribbon tab is set to enabled="false", both its imageMso as well as its text are still there and greyed out, which is the behaviour I expect.

But when a dynamicMenu in my Word Ribbon tab is set to enabled="false", its imageMso is not visible anymore. (Its text is still there and greyed out, which is the behaviour I expect.)

How can I disable a dynamicMenu and still show its imageMso?

Kind regards

Nora

Unexpected "Property Update" entry in the Undo stack

$
0
0

Setting: C# VSTO add-in.

I have two nearly identical code paths that involve inserting a ContentControl. Here is the summarized code path for both. In this code, MyItemA and MyItemB are derived from MyItem.

public MyItem AddPictureItem(...) { Word.Range range = getRangeFromSelection(); CustomUndoRecordStart(range.Application, string.Format(…)); Word.ContentControl control = range.ContentControls.Add(Word.WdContentControlType.wdContentControlPicture); [...set control properties...] control.Range.Select(); MyItemA item = CreateItem(ContentType.Picture, control) as MyItemA; item.SetSomeProperties(...); CustomUndoRecordEnd(range.Application); return item; } public MyItem AddTextItem() { Word.Range range = getRangeFromSelection(); CustomUndoRecordStart(range.Application, string.Format(…)); Word.ContentControl control = range.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText); [...set control properties...] MyItemB item = CreateItem(ContentType.Inline, control) as MyItemB; item.SetSomeProperties(...); CustomUndoRecordEnd(range.Application); return item; }

Both calls to CreateItem(...) follow the same path, which updates data stored in a CustomXmlPart.

    Office.CustomXMLNode rootNode = customXmlPart.SelectSingleNode(
        String.Format("//*[local-name() = '{0}']", CUSTOMXMLPART_NAME));
    rootNode.AppendChildSubtree(contentToAdd);

This update is the puzzle. In AddPictureItem, it produces exactly what is expected: one custom undo record.  AddTextItem also produces the custom undo record, but it is followed by a Property Update record tied to that CustomXmlPart update. (Omit the call to AppendChildSubtree and the entry does not get added.) 

I have stepped through both routes meticulously, confirming that the above is the only place where the paths differ (although AddPictureItem comes from a ribbon button and AddTextItem from a context menu item). I have even changed AddTextItem to create the same ContentControl type as AddPictureItem, with only the ContentControl properties differing, and still the behavior difference persists. Why? Is the invocation path significant? And how can I get them to behave the same?


Getting access to XML Node

$
0
0

Hi,

This could be the wrong forum, but it is a follow on to an earlier question I posted here about the WordOpenXML string defined by a Word rich text content control.

I am basically trying to get access to the "body" node of the XML.  I added the XML as a customXMLPart to a word document and then used my CC Mapping Tool add-in to determine the xPath of the node of interest.  That is shown in my code below.  However, when I run this code I am getting an error about an undefined namespace reference. 

For the code to work, you need a reference to the Microsoft Office XML 6.0 object library and a document containing a single rich text content control containing text.

Can anyone assist with the correct XPath statement to access this node or how to define the missing ns references that the complier complains about?

My ultimate goal (perhaps fruitless) is to attempt to create a rich text CC change event.  If I can get a manageable chuck of string text to continuously compare with a reference chunk of sting text then viola.  The problem appears to be constantly changing rsid values in the WordOpenXML string.  If I can isolate just the "body" string and strip out those rsid values then I may have some success.

Thanks.

Sub ScratchMacro()
Dim oXDoc As New MSXML2.DOMDocument
Dim oNode As MSXML2.IXMLDOMNode
oXDoc.LoadXML (ActiveDocument.ContentControls(1).Range.WordOpenXML)
oXDoc.setProperty "SelectionLanguage", "XPath"
Set oNode = oXDoc.SelectSingleNode("/ns0:package[1]/ns0:part[3]/ns0:xmlData[1]/ns11:document[1]/ns11:body[1]")

End Sub


Greg Maxey Please visit my website at: http://gregmaxey.mvps.org/word_tips.htm

Open Word File on server in Client Machine and Save File back to Server in Vb.net

$
0
0

Hi,

I am developing one windows application in vb.net in visual studio 2012.I have some word documents(.docx) in server at perticular folder.The VB.NET Windows application is installed in client machine.I want to open that word document(in server) from client system.I want to edit that document, after editing i want to save that document back to server.How to implement above scenario.

Viewing all 4350 articles
Browse latest View live


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