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

Using PowerShell to update variables within a Word document...

$
0
0

I have created a PowerShell script to create a user in Active Directory, create their home folder and assign their permissions, assign their Office 365 licensing and email various individuals with our organization to tell those individuals they need to do their part to welcome the newcomer.  I have also created a Word document that I would like to update and then send on to HR with this individual's specifics to so they would have this to hand to the newcomer on their first day, HOWEVER, I can not figure out how to accomplish this last piece.

I can open the document in PowerShell and I can manipulate the variables in VBA but I can't figure out how to change the variable from within PowerShell.  So, for example, the PowerShell script has a variable $username.  The Word document has a textbox named username.  When I try:

$range.username.text = "$username"

I get an error that tells me:

Property 'Text' cannot be found on this object; make sure it exists and is settable.

I'm sure it is either a formatting error on my part or how I am calling the variables but I have been unsuccessful in finding a good lead in how to resolve this.

Any assistance would be greatly appreciated!


Update all Content Controls with same name

$
0
0

Hello,

I am trying to update content controls in my MS Word document using a macro. It's working, but only for one of the content controls with that name. Content Controls can be called the same name, but the unique id will be  unique. One content control is customer name, which will be in the document up to 27 times, or so. I just want to be certain all customer name content controls are all updated with the same information, so all customer name controls are updated, not just one.

Here is my code:

Sub GetOpportunityDetails()
On Error GoTo GetOpportunityDetailsError
    Dim cnnOpportunityDetails As New ADODB.Connection
    Dim rstOpportunityDetails As New ADODB.Recordset

    cnnOpportunityDetails.Open "Provider=SQLOLEDB;" & _"Data Source=(local);" & _"Initial Catalog=AdventureWorks2014;" & _"Trusted_Connection=yes;"

    Dim strSQL As String
    strSQL = "SELECT TOP 1 * FROM [AdventureWorks2014].[HumanResources].[Employee]  Where BusinessEntityId = 12" & ";"
    Debug.Print strSQL

    rstOpportunityDetails.Open strSQL, cnnOpportunityDetails, adOpenStatic

   ' rst.MoveFirst
    Dim oCC As ContentControl
    'Note it only updates one AttentionName, when there are multiple ones:
    Set oCC = ActiveDocument.SelectContentControlsByTitle("AttentionName").Item(1)
    oCC.Range.Text = rstOpportunityDetails![JobTitle]




    'Set oCC = ActiveDocument.SelectContentControlsByTitle("CustomerServiceName").Item(1)
    'oCC.Range.Text = "Customer Service Name."

    'Format(DateValue(Now()), "mmm_dd_yyyy")

   ' ActiveDocument.SelectContentControlsByTitle("ProposalDate").Item(1) = "ABC"

'    Set street1 = ActiveDocument.SelectContentControlsByTitle("Address1").Item(1)
'    Set street2 = ActiveDocument.SelectContentControlsByTitle("Address2").Item(1)
'    street1.Range.Text = rst![Address1_Street1]
'    street2.Range.Text = rst![Address1_Street2]


GetOpportunityDetailsExit:
    On Error Resume Next
    cnnOpportunityDetails.Close
    Set rsOpportunityDetails = Nothing
    Set cnnOpportunityDetails = Nothing
    Exit Sub


GetOpportunityDetailsError:
    MsgBox "Error " & Err.Number & vbCrLf & Err.Description, vbExclamation, "Error " _& "Error Loading Opportunity Detail. Please contact IT Help Desk for Support."
    Resume GetOpportunityDetailsExit

End Sub


John

vba xml can I pass a variable to obtain selectsinglenode values

$
0
0
<<?xml version="1.0"?><arrayEnvironment><data><setup><environment>prod</environment><repository></repository><clientCabinetID></clientCabinetID><BusinessCabinetID></BusinessCabinetID><HomePath></HomePath><NavPath></NavPath><clientPath></clientPath ><businessPath></businessPath></setup><setup><environment>pre-prod</environment><repository></repository><clientCabinetID></clientCabinetID><BusinessCabinetID></BusinessCabinetID><HomePath></HomePath><NavPath></NavPath><clientPath></clientPath ><businessPath></businessPath></setup><setup><environment>dev</environment><repository></repository><clientCabinetID></clientCabinetID><BusinessCabinetID></BusinessCabinetID><HomePath></HomePath><NavPath></NavPath><clientPath></clientPath ><businessPath></businessPath></setup></data></arrayEnvironment>

I have two xml files. The first xml file stores a variable. The second xml file stores data.

My code reads the first xml file to obtain the variable value.

I want to use this variable to obtain data in the second xml file.

Ive used the sample here
http://excel-macro.tutorialhorizon.com/vba-excel-read-data-from-xml-file/

I think .SelectNodes will achieve what Im wanting.
Looking at  .SelectNodes syntax the actual search text is in single quotes eg 'Fantasy'eg this example

Set Nodes_Fantasy = oXMLFile.SelectNodes("/catalog/book/title[../genre = 'Fantasy']/text()")

If I want to pass my variable would the following syntax work 

Set Nodes_Fantasy = oXMLFile.SelectNodes("/catalog/book/title[../genre = InsertVariableHere]/text()")


How can this be achieved. should I be using another method

my xml files are attached.

TIA

The first xml file stores the value.

CurrentEnvironment.xml

read node currentEnvironment

<?xml version="1.0"?><setup><environment><currentenvironment>prod</currentenvironment></environment></setup>

the second xml contains data i need to retrieve

environmentURLs.xml

Use currentEnvironmentVariable to read and obtain values in this xml file


Programmatically Enforcing Merge Formatting

$
0
0

Hello,

I have a custom c# reporting tool that creates a Word document. During testing it was discovered that when text is copied from one document and pasted into the documented created by the tool the preferred font is only maintained if the Merge Formatting is selected. We're using Word 2010 or higher.

Instead of training the users to select Merge Formatting I wanted to see if there is a way to programmatically set this in c# as part of the reporting tool. In VBA I found that this can be accomplished using the following paste and format option:

wdUseDestinationStylesRecoveryUses the styles that are in use in the destination document.


Is there a similar paste and format option in c#?

To further clarify, I want to be able to set the following using c# code rather than setting within Word.

  1. Click theMicrosoft Office Button
  2. ClickAdvanced, and then scroll down to the Cut, copy, and paste section.
  3. Select the settings that you want with the following boxes.
    • Pasting within the same document
    • Pasting between documents
    • Pasting between documents when style definitions conflict
    • Pasting from other programs

For more information about these options, see the Options for pasting within and between documents, and from other programs of this article.

  1. To use settings for the smart cut-and-paste option, select theUse smart cut and paste check box, click Settings, and then select the settings that you want. For more information, see the Settings for the smart cut-and-paste option section of this article.
  2. ClickOK.

Thank you in advance for any information.

Regards,

Chris

Code in Word template is actually updating template rather than new Word doc

$
0
0

I've written some code to take a user form's data and update content controls.  It works fine when testing the template.  It doesn't work when testing in new doc created via the template.  The code executes when new doc is created, the user form is displayed and I'm able to fill the form and submit it, but the template is getting updated rather than the new doc.  I'm sure this is something really basic that I'm missing ... since I seldom create code.  I've attached the code below.

Many thanks in advance,

Chris

Private Sub CommandButton_Update_Click()

    Dim cc As ContentControl
    Dim ccValue(12) As String
    Dim formValue(12) As String

    'collect form values
    formValue(1) = UserForm1.TextBox_ClientName.Value
    formValue(2) = UserForm1.TextBox_SowDate.Value
    formValue(3) = UserForm1.TextBox_ClientProject.Value
    formValue(4) = UserForm1.TextBox_City.Value
    formValue(5) = UserForm1.TextBox_State.Value
    formValue(6) = UserForm1.TextBox_ClientName.Value
    formValue(7) = UserForm1.TextBox_ProjectTitle.Value
    formValue(8) = UserForm1.TextBox_ClientPm.Value
    formValue(9) = UserForm1.TextBox_Bpfl_Pm.Value
    formValue(10) = UserForm1.TextBox_ProjectDate.Value
    formValue(11) = UserForm1.TextBox_ProjectTitle.Value
    formValue(12) = UserForm1.ComboBox_Services.Value
    
    For x = 1 To 12
        Set cc = ThisDocument.ContentControls(x)
        cc.Range.Text = formValue(x)
    Next x
    
    Unload Me

End Sub

Spell check and Grammar API to integrate

$
0
0

I would like to find out if there is an API out there to integrate Spell checker and grammar checker with third party tool. Of course your local system should have MS Office installed and this 3rd party tool calls spelling or grammar checker and provides the result in 3rd party tool.

Is this possible? Can someone point me in right direction to find out what needs to be done.

Thank you,

Anju

Accessing HeaderFooter.Range leaves header/footer open (VSTO, .NET, Word)

$
0
0

Hi,

we have an addin which lets the user put a textbox with a string into the header on every page.

The problem is if you access HeaderFooter.Range or .Shape the header gets activated but will not be deactivated anymore after you accessed it.

This is apparent if you have the page margin set to 0 and header / footer also to 0.

So to reproduce:

- Create a document with no margin and no header and footer height.

Write something into the first line to see the header later.

Save the doc.

Create an addin with the following code.

private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Globals.ThisAddIn.Application.DocumentOpen += new Word.ApplicationEvents4_DocumentOpenEventHandler(Application_DocumentOpen);
        }
        void Application_DocumentOpen(Word.Document doc)
        {
            foreach (Word.Section section in doc.Sections)
            {
                foreach (Word.HeaderFooter header in section.Headers)
                {
                    var rng = header.Range;
                }
            }
        }

and open the label document.

You see a small header on top of the page which comes from activating the header.Range but word does not deactivate it after accessing.


Is there a possibility to close the header after accessing it?

Thank you very much

Best regards

Mark


Regards Mark




Mandatory Fields Word 2010

$
0
0

Hello,

I have a permit document which our maintenance department are going to be completeing on the computer before printing out etc. What I would like to do is have some parts of the permit mandatory and if possible, not allow it to be printed unless all mandatory fields are filled in.

I have searched the net for help but all I have found is overly complicated macros. I have tried to look at using form fields but cant get them to do what I want.

Any help would be greatly appreciated.

Thanks,

Alex


Convert Text to table using Macros

$
0
0

Hi Friends,

I would like to ask your help on how to convert text to table using macros.

I receive the text like this example:
Text1 tex1. Some/text. [text1] This is just an example.

We need to create table with four (4) columns.

"Text1" will be on the second column.

"text1. Some/text. [text1] This is just an example." will be on the fourth column.

There is a lot of text formatted like this example, so it really helpful if it can be automated using macros.

Thanks!

Problem distributing ‘This Document’ VBA Macros to Users.

$
0
0

I have developed some VBA that enable a ‘Merge to Email’ to:

  • Personalise the Subject with Merge Fields, 
  • Send Attachments.

Most of the logic is in a Single ‘MergeToEmail_Module’.  However some of the Logic has had to remain In ‘ThisDocument’ – namely:

  • Document_Open,
  • WORD_Application_MailMergeBeforeRecordMerge,
  • Document_Close.

I use:  Dim WithEvents WORD_Application As Application in ‘ThisDocument’ so I can use WORD_Application_MailMergeBeforeRecordMerge, but apparently I can’t use that in a Module. I’m using WORD 2007, but use ‘Late Binding’ so it should work with any version of WORD from 2007 on. 

At present this is all working fine, but it’s in a “.docm” Document. If I put it in a “.dotm” Template the Subroutines in ‘ThisDocument’ are not called. I have not yet tried putting them in a ‘STARTUP Add-In’, as I suspect they will still not work. 

Is there any way around the problem?

Hyperlinks with Chinese characters cannot be converted by ExportAsFixedFormat in Office 2007

$
0
0

I tried with the same computer configuration, Office 2013 worked, but Office 2007 not. Is it a bug of the SaveAsPDFandXPS add-in for Office 2007? Thanks.

Here is the screen snapshot of the corrupted hyperlinks

https://social.msdn.microsoft.com/Forums/getfile/704984



Word to PDF conversion, generated PDF is not searchable

$
0
0

Hi 

I am using C# code to convert to word to pdf. We created exe out of C# coade and using in our java program. The pdf is creating successfully but the problem is it is not searchable. It is creating as bitmap instead of text. I need your help here. I am pasting my code below. Your help is appreciated. Thanks . Sridhar

                                

using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using Microsoft.Office.Interop.Word;
namespace DocToPdfConverter
{

    public class DocToPdfConverter
    {

        static int Main(string[] args)
        {
            String inputFileName = args[0];
            String outputFileName = args[1];
            Console.WriteLine("Started Converting Word Document To Pdf >> .....");
            DocToPdfConverter dc = new DocToPdfConverter();
            Microsoft.Office.Interop.Word.Application application = new                          

                                 Microsoft.Office.Interop.Word.Application();

            dc.ConvertToPdf(inputFileName, outputFileName, application);
            Console.WriteLine("Successfully Done With PDF Conversion.");
            return 0;
        }

        public void ConvertToPdf(String inputFileName, String outputFileName,                                  Microsoft.Office.Interop.Word.Application application)
        {
            object originalFormat = null;
            object routeDocument = false;
            object saveOption = null;
            Word.Bookmarks bookmarks = null;
            string bookmarkNames = string.Empty;
            String outName = string.Empty;
            try
            {
                object missing = System.Reflection.Missing.Value;
                object readOnly = false;
                object isVisible = true;
                object inputsFileName = inputFileName;
                application.Visible = true;
                application.DefaultWebOptions().AlwaysSaveInDefaultEncoding = true;
                Word.Document aDoc = application.Documents.Open(ref inputsFileName, ref missing,
                ref readOnly, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref isVisible);
                saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
                originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;
                object fileFormat = WdSaveFormat.wdFormatPDF;
                object outputFileNames = outputFileName;


                if (aDoc != null)
                {
                    Console.WriteLine("Before Export.......");
                aDoc.ExportAsFixedFormat(  outputFileName, WdExportFormat.wdExportFormatPDF, false,
                                                 WdExportOptimizeFor.wdExportOptimizeForPrint,
                                                 WdExportRange.wdExportAllDocument, 0, 0,
                                                 WdExportItem.wdExportDocumentContent, true, true,
                                                 WdExportCreateBookmarks.wdExportCreateHeadingBookmarks,                                                                            true,true, false, ref missing);
                Console.WriteLine("After Export..............");
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                application.Quit(ref saveOption, ref originalFormat, ref routeDocument);
            }

        }
    }
}







ExportAsFixedFormat works differently when export a Word Document opened in "ReadOnly" mode.

$
0
0

I have a word document that has 256 pages and some paragraphs with "keep with next" property.

When open the word document in "Read/Write" mode, and call ExportAsFixedFormat to convert it to pdf, the output has 256 pages.

When open the word document in "ReadOnly" mode, and call ExportAsFixedFormat to convert it to pdf, the output becomes 243 pages.

Why is the pagination calculation different in "ReadOnly" mode? Thanks

Using get_Style, set_Style, get_BaseStyle, set_BaseStyle, etc. in C#

$
0
0

I have been using Word interop with VB for a while, including working directly with properties of Word styles. In automating Word with C#, I am coming across new (to me) and different usage such as get_Style, set_Style, get_BaseStyle, set_BaseStyle.

What I am looking for is a reference or documentation describing this approach, as well as what other, similar, methods might be available for different Word objects. I'm coming up empty. (I assume documentation is lacking because these are dynamically created methods?)

I would love to know more background on this and understand which Word objects have these "extra" methods available in C#. i.e., a solid explanation of which Word objects have these and why. And curiously, why I can't seem to find any mention of them when searching the web.

Thanks

Check if Document is in Compatibility Mode using c#

$
0
0

Hi,

I need to check if a doc is opened in Compatibility Mode in order to know if the button "File->Info->Convert" exists.

Is it possible? I need it for word, excel and power-point.  The version of office is 2013.

Another question: is it possible to press the button ("File->Info->Protect document") from the code?

Thanks.


Documentation on how fonts are grouped?

$
0
0
I was recently hired in IT/Data for a small lettershop & mailing firm and have been tasked with educating myself on font management.

Everything is well documented except the logic by which Windows/Office/InDesign group installed fonts (by typeface/family/style etc) to generate a font list for the user.

Simple example; When you italicize a sentence in Arial, Word will look for an ArialItalic font file.  If none exists, Word will 'improvise' italics by slanting the characters.

By what process does Word decide font file X is "Arial Italic"?  Where is this logic documented?

Any help would be great, need to develop a professional understanding of this and I'm having a hard time even getting off the ground!

Thanks,

-P

VBA Assign variable from FIND found results

$
0
0

I am trying to find a style and assign the contents of the style to a variable.  Obviously, I am using the .text property incorrectly.  How do I assign the text found in the style to a variable.

Dim rng As Range
Set rng = ActiveDocument.Content
    With rng.Find
        .ClearFormatting
        .Style = ActiveDocument.Styles("Disc")
        .Forward = False
        .Wrap = wdFindStop
        .Format = True
        .Execute
        If .Found = True Then
              sPrev = rng.Text

        End If
    End With

Thanks

How to create own Blog provider for Ms word.

$
0
0

Hi All,

I have created own web site for bloging and now I want to link it with word to publish my blogs from MS word, Have seen that there are some Blog provider as wordpress , but Now I want to develop my own API to publish the blog directly to my own web site. 

Please provide any link or any clue where to start from. 

Thanks 

Santosh Jha

Providing and managing template add-ins

$
0
0

Hi Cindy

Thanks for your help - yet again!  I have two scenarios where I want to use these Macros. 

The first is in conjunction with our own software.  This enables our Users to specify any WORD Document/Template as a 'Template' they wish to use.  They can then define the Attachments they want to send, Assign Categories to the Recipients, Set a Reminder, or create an OUTLOOK Task for the Sender - or any other member of staff. 

If a Merge-to-Email is required, our system copies the master .docm Document that contains the necessary WORD Macros that enable personalisation of the E-mail Subject with Merge Fields and the sending of Attachments.  This is written as a Temporary Document in a defined location.  We then replace its BODY with the Document.BODY from their selected WORD Document/Template.  If it's not a Merge-to-Email then the Macros will not be required so it just copies their selected WORD Document/Template as the Temporary Document.  Our software then opens the Temporary Document and passes control to WORD, where the User can do what they like and complete the merge.

The second is without using our software.  Here, based on what you have just told me, what I would like to do is as follows:

  • develop a WORD Add-In that anyone can put in their STARTUP Folder,
  • until the user starts a Merge-to-Email it does nothing, so it would just look like the usual:

  • as soon as the User starts a Merge-to-Email, it ask them whether the would like to personalise their Subject with Merge Fields or send Attachments, if they say yes, then the mailings tab would reconfigure itself to my existing configuration to enable them to do what they want.

I would need to replace my first button with WORD's original:

So that if they suddenly decide they don't want to send E-mails they can revert to some other option.  If they do then it would revert to WORD's default Mailings Tab configuration.

Do you think it's doable?  Or is there some snag that I can't see? 

I'd also like to know whether there is any way I can make an Add-in available to all User's on a particular machine, or does the Add-In neeed to be loaded into everyone's own STARTUP Folder?

Thanks
Brian


[SOLVED] Recording new macro in Word 2010

$
0
0

None of the Word 2010 installations at our site are allowing actions to be performed during macro recording in Word. We select Record Macro and get the "casette" cursor. No actions (like enter text, select text, find text) can be executed. After selecting pause or stop recording, actions are allowed.

the macros are being recorded to normal.docm. the macro Sub is written to normal.docm, but has no contents.

Viewing all 4350 articles
Browse latest View live


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