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

How to insert levelled bullets with my current code snippet?

$
0
0

Hi All,

I have two buttons, one which inserts level 1 bullets and another which inserts level 2 bullets 

 The problem : Here if I click on the level 1 button it inserts a numbered bullet , like "1."  and I click on second button , it inserts "1.1."  and now if I press the first button to insert "2 ."  it inserts fine,but the second button click does not insert 2.1 ,instead it inserts "1.2" Have been stuck on it for days.Any help is much much appreciated .Thanks      

This is what I have tried so far,

    //to insert level -1 numbered bullets

private void button4_Click_1(object sender, RibbonControlEventArgs e)
        {
   Word.ListGallery listGallery = Globals.ThisAddIn.Application.ActiveDocument.Application.ListGalleries[Word.WdListGalleryType.wdOutlineNumberGallery];
                 oPara = oDoc.Content.Paragraphs.Add(range);
                 listFormat = oPara.Range.ListFormat;
                this.ApplyListTemplate1(listGallery, listFormat, 1);
                range.ListFormat.ListLevelNumber = 1;
         }

//to insert level-2 bullets (1.1,,2.1 etc )

 private void button5_Click(object sender, RibbonControlEventArgs e)
        {

     
            Word.ListGallery listGallery = Globals.ThisAddIn.Application.ActiveDocument.Application.ListGalleries[Word.WdListGalleryType.wdOutlineNumberGallery];

                oPara = oDoc.Content.Paragraphs.Add(range);
                  listFormat = oPara.Range.ListFormat;
                this.ApplyListTemplate1(listGallery, listFormat, 2);
                oPara.Range.ListFormat.ListLevelNumber = 2;

            }
Here is my apply list template:  

private void ApplyListTemplate1(Word.ListGallery listGallery, Word.ListFormat listFormat, int level = 2)
        {
            listFormat.ApplyListTemplateWithLevel(
                listGallery.ListTemplates[level],
                ContinuePreviousList: true,
                ApplyTo: Word.WdListApplyTo.wdListApplyToSelection,
                DefaultListBehavior: Word.WdDefaultListBehavior.wdWord10ListBehavior,
                ApplyLevel: level);
        }

                              

Can not get he ActiveDocument.SaveAs2 method to work on Word 2013

$
0
0

For many years I have automated office applications from Visual Basic through the Office Object Model. This has been working fine for all versions from 2003 but failed when I upgraded to Office 2013.

With Word 2013 the SaveAs2 method seems to ignore the parameters and instead always pops up the File SaveAs dialog. Irrespective of save or cancel the method then always returns the error 4198.

The SaveAs2 method works fine in Word 2010 as well as SaveAs in earlier versions. According to the documentation for 2013 it should work the same way for the new version, but so far I’m stuck with this problem.

I’m using Microsoft Office Home and Business 2013 on a Windows 8 system. I’ve also tried the SaveAs2 directly in Microsoft Word VBA. The macro below gives exactly the same sad result.

Public Sub MySave()

Dim MyName As String

MyName = "TestDocument.doc"

ActiveDocument.SaveAs FileName:=MyName, FileFormat:=wdFormatDocument

End Sub

I seem to be completely stuck. Does anyone know what the trick is here? 

Excel 2010 VBA Code to find and replace text in a Word Document's Footer

$
0
0

Hi all,

I have a Excel 2010 VBA subroutine that copies output to a word template.

I've noticed that the general find and replace text code below doesn't work on footers.  If it did, this would be the code:

    With wd.Content.Find
        .Text = "($Adviser_name)"
        .Replacement.Text = Sheets("Export").Cells(58, 2).Text
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With


The field that needs to be filled in is located in the first page footer on Section 2 of the document.

Thanks!

References bold/italic

$
0
0

Hi all,

I want to develop an application that insert a reference correctly.

I am new to VBA in Microsoft Word and want to ask if someone can help me out with this.
What I want to do is that the user can click on a button so he gets a screen where he can fill in some fields and then press a button which will generate a paragraph after the cursor position.

The screen and GUI is not the problem but I don't know how I can make just one word bold or Italic or something.
Can someone help me out with this?

Write a short example with just three words in it or something.

Thank you!

Autocomplete TextBox

$
0
0

Hi

I searched a lot of threads but couldn’t find an answer to this question: How to get autocomplete feature in textbox of Microsoft Word?

If anyone could please help it would be great.

Many Thanks for your time.

Thanks

Normal numbered bullets continuation after table

$
0
0

Hi All,

I have a button that inserts  numbered bullets in my document like

1.

2.

3.

I also have a table with outline numbered bullets like 

//table 

1)

2)

//end of table 

Now on pressing the bullets button again outside the table , I get 

"3) "---> here I' am getting the continuation of the list in table in my document,how to reset the numbering to 

4. pragmatically? 


Order list and Sub-list in a table in Ms Word is not working.

$
0
0

In normal routine, when working with an order list if their is any sub-list of a point then just by pressingTab key at starts of the line, it makes it the sub-list of a list.

E.g 

1 . List 1

1.1 By pressing tab key at the start of this line makes it sub list of 1.

But when this task is performed in table's Column then it just moves to next cell in the table.

How to make the list and sub-list style in the cell of a table. 

Automated Save As after MailMerge and .Destination = wdSendToPrinter in VBA

$
0
0

Hi Professionals,

I am running Win7 MS Office 2010  and Visual Basic 6.5.

I am trying to automate a .pdf Output and came so far to only enter a filename for the printed .pdf. Since the outfile is to have a similar name as the inputfile, the save as could be automated as well.

Now for my code so far:

Sub Macro2()

Dim x, i As Integer
Dim y As String
x = 1
i = 1
y = x

Do While i < 999

    If Dir("D:\Video\list\b-" + y + "\") = "" Then

        i = i + 1
        x = i
        y = x

      Else

    ActiveDocument.MailMerge.OpenDataSource Name:="D:\Video\list\b-" + y + "\" + y + ".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=D:\Video\list\1.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:G" _
        , SQLStatement:="SELECT * FROM `Sheet1$`", SQLStatement1:="", SubType:= _
        wdMergeSubTypeAccess
    ActiveDocument.MailMerge.ViewMailMergeFieldCodes = wdToggle
    With ActiveDocument.MailMerge
        .Destination = wdSendToPrinter
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
       .Execute Pause:=False

        End With

    i = i + 1
    x = i
    y = x

    End If
Loop



End Sub

Is there a way to insert something like

With ActiveDocument.MailMerge .Destination = wdSendToPrinter .SuppressBlankLines = True With .DataSource .FirstRecord = wdDefaultFirstRecord .LastRecord = wdDefaultLastRecord End With

.SaveAs FileName:="C:\Users\user\Documents\b-" + y + "XXX.pdf"

.Execute Pause:=False

Help is much appreciated!

Greetings


Scrolling

$
0
0

After we execute some of our macros the text where the cursor is placed is sometimes off the bottom of the screen. Is there a programmatic way of forcing Word to scroll so that the cursor is in the centre of the screen?

How do I create a new word document and add a block of text stored in a variable to it in C#?

$
0
0

Hi,

I have some code that has a range of text stored in a variable called originalText. How do I create a new document and put the contents of originalText in it? Also, the text inside orginalText keeps changing based on a set of if conditions that I have so I want a new document to be created every time a new if condition appears.

Many thanks in advance!

automation error -2147483640

$
0
0

Hi

When using Microsoft Word 2011 for Mac , I tried the calendar formats and it gave me this error when opening : automation error -2147483640 . I said clicked okay, then a box popped up saying I must select a month and year. When selecting the month and year and clicking OK, it would say I must select a month. Why does it not let me select this and finish my calendar ?


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

Event Handler Interrupts Undo/Redo Records

$
0
0

I have an MS Word VBA project which defines an Event handler class for the purpose of overriding the DocumentBeforeClose event.  The class does not implement any other Event procedures, however it appears that merely instantiating the class causes Word to attempt invoking other Event procedures that are not defined.

Specifically, my users have a workflow in which they select a block of text and type to overwrite it, then attempt to Redo that typing.  With my Event handler class instantiated, the first keypress seems to attempt to trigger a WindowSelectionChange event in my class (which no-ops) and that action interrupts the "typing" record on the undo/redo stack.  If the user continues to type a full word (e.g. "text", where the first "t" overwrote the previous selection) and then presses Redo, only the characters after the failed event will be added (e.g. "ext" in this example).

Is there any way I could get around this?  I've investigated the UndoRecord object and CustomRecord concept, but can't think of any way to apply it here (and I need to support use of MS Word 2007 with my project anyway).

Copy table content with C #

$
0
0

Hello everyone, 
I'm trying to develop an Add-In for Microsoft Word (I am following these guides: http://msdn.microsoft.com/en-us/library/cc442946.aspx) and I would like to copy the contents of one table to another.

For now I managed to do it in this way:

table1.Cell(1, 0).Range.Text = table2.Cell(1, 0).Range.Text

This only works with plain text but not with pictures or formatted texts.

Could someone explain to me how I have to do to copy all the contents?

VBScript - Identifying Rows that are too large for a page

$
0
0

I have tables in MS Word, and I am trying to see what the height of a row is in that table.  As the tables are, the Rows HeightRule is set to Auto (wdRowHeightAuto).  From what I have noticed the Height of the Rows are set to 9999999 points when the HeightRule is Auto.  And when I convert the rows to wdRowHeightAtLeast, the Height is changed to 12 points regardless of the content of the cells in that row.

Overall question,

Is there any way to read the actual height of the row as opposed the "at least" value?

OR

Is there a way to identify if a row should be allowed to break across a page when AllowBreakAcrossPages is set to True?

Note:

 I tried setting the HeightRule to wdRowHeightExactly, all that did was make the rows have a height of 12 points.  If at all possible I would like to get a script working to do this for me as opposed to manually like I have been.


How to insert picture inside MS Word text box using C#

$
0
0

Hi,

I have a picture that I want to insert into text box or a rectangle by replacing a word like <Image> which written inside the shape with this picture

I have searched much and found this code that replace the all text in the document including the text in the text boxes and shapes:

public void FindandReplace(Word.Document doc, string Findtext, string ReplaceText)
{
	Word.Range myStoryRange = doc.Range();

	//First search the main document using the Selection
	Word.Find myFind = myStoryRange.Find;
	myFind.Text = Findtext;
	myFind.Replacement.Text = ReplaceText;
	myFind.Forward = true;
	myFind.Wrap = Word.WdFindWrap.wdFindContinue;
	myFind.Format = false;
	myFind.MatchCase = false;
	myFind.MatchWholeWord = false;
	myFind.MatchWildcards = false;
	myFind.MatchSoundsLike = false;
	myFind.MatchAllWordForms = false;
	myFind.Execute(Replace:Word.WdReplace.wdReplaceAll);

	//'Now search all other stories using Ranges
	foreach(Word.Range otherStoryRange in doc.StoryRanges)
	{
		if(otherStoryRange.StoryType != Word.WdStoryType.wdMainTextStory)
		{
			Word.Find myOtherFind = otherStoryRange.Find;
			myOtherFind.Text = Findtext;
			myOtherFind.Replacement.Text = ReplaceText;
			myOtherFind.Wrap = Word.WdFindWrap.wdFindContinue;
			myOtherFind.Execute(Replace:Word.WdReplace.wdReplaceAll);
		}

		// 'Now search all next stories of other stories (doc.storyRanges dont seem to cascades in sub story)
		Word.Range nextStoryRange = otherStoryRange.NextStoryRange;
		while(nextStoryRange != null)
		{
			Word.Find myNextStoryFind = nextStoryRange.Find;
			myNextStoryFind.Text = Findtext;
			myNextStoryFind.Replacement.Text = ReplaceText;
			myNextStoryFind.Wrap = Word.WdFindWrap.wdFindContinue;
			myNextStoryFind.Execute(Replace:Word.WdReplace.wdReplaceAll);

			nextStoryRange = nextStoryRange.NextStoryRange;
		}

	}
}

I want to modify this code to be able to replace the text I need to replace with a picture

Any suggestion?

Thank you in advance

Error protect document being co-authored

$
0
0

Hi,
I have a problem with my word addin in word 2010.

The addin handles a special type of documents and support the automatic refresh of document parts. Usually, the document is protected. Only during automatic refresh, the document gets unprotected for a short time.

Everything works fine. Now the users start to share the documents via SharePoint and start to work with co-authoring.  At this point, I've noticed that the document protection got lost. After investigation I found out, that the protection method get the following exception:

The Protect method or property is not available because this command is not available in documents that are being co-authored. HResult -2146823683

The Unprotect method works without any problem. Curiously, if i try to protect the document manually in the same situation, using Developer -> Restrict Editing -> "Restrict Formatting and Editing" Taskpane -> Click "Yes, Start Enforcing Protection", the document protection is enabled. I tried to record this action using "record macro" function. The VBA code seems similar to my C# code and get the same error. So only the manual click on the taskpane button works.

Does anyone has an idea how I can protect the document via code? Is there a workaround?

Thanks in advance for your help!

Best Regards
Dirk Loeb


Accessing Selection.StoryType from Reviewing Pane leads to run-time error

$
0
0

Hi,

I found a very weird behavior of Word 2010 and VSTO (same applies for VBA though).When selection is in the Reviewing Pane, running the line below will raise a run-time error.

The erroneous code:

public static void Application_WindowChangeSelection(Selection sel){ if (sel.StoryType != WdStoryType.wdMainTextStory)

...

}

The error:

So after a quick debugging I found that if the selection is within the Reviewing Pane, then when trying to access the StoryType property, will throw exception:

Error HRESULT E_FAIL has been returned from a call to a COM component.

Question is why this happening and how can I detect when selection is in Reviewing Pane and eliminate this run-time error?
I tried catching the exception and returning from the ChangeSelection event in that case, but it then leads to a strange behavior where the selection in this pane remains, even if the user is making another selection.

Thanks,

Etai.

Programmatically convert Office 2013 Word docx to PDF

$
0
0

Back in Office 2007/2010, I had a piece of C# code that used the Microsoft.Office.Interop.Word assembly reference and I would convert a Word doc into a PDF like so:

//Creating objects of word and document
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();

..other code, then...

 oWordDoc = oWord.Documents.Open(ref pptPrintFilePath, ref missing,
                    ref readOnly, ref missing, ref missing,
                    ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing,
                    ref isVisible, ref missing, ref missing,
                    ref missing, ref missing);

                if (oWordDoc != null)
                {

                    oWordDoc.ExportAsFixedFormat(pdfFilePath,
                        WdExportFormat.wdExportFormatPDF,
                        false,
                        WdExportOptimizeFor.wdExportOptimizeForPrint,
                        WdExportRange.wdExportAllDocument,
                        0,
                        0,
                        WdExportItem.wdExportDocumentContent,
                        true,
                        true,
                        WdExportCreateBookmarks.wdExportCreateNoBookmarks,
                        true,
                        true,
                        false,
                        ref missing);
                }

As time marches on, we are in Office 2013 but there is no .Interop .dll.

How would this be accomplished in Office 2013?

Thanks!


STom

method 'comaddins' of object '_application' failed while looking for the registered COMAddins

$
0
0

We have this simple piece Where in we are registering an Addin and trying to find the Addin by looping through the list of Addins. This is not consistently reproducible on all the machines and we started seeing this on a client machine. We don't see anything wrong with the code either. We didn't see much on any of the forums. Please help.

When the code hits the for loop we get this error. Runtime Error -2147310770(8002801d). method 'comaddins' of object '_application' failed.

For Each oAddin In oWordApp.COMAddIns

Sub Main()
    
    Call RegisterAddin

    Dim oWordApp As New Word.Application
    
    Dim oAddin As Office.COMAddIn

    For Each oAddin In oWordApp.COMAddIns
        If oAddin.DESCRIPTION = "TestingCom Addin" Then
            oAddin.Connect = True
        End If
    Next




Viewing all 4350 articles
Browse latest View live


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