Getting a Range

You have several ways to get a range in a word document. VSTO have already considered several document-level collections such as Paragraphs, Sentences, Words and Characters that return Range Object. The most common way to get a Range is to use the Range method on the Documen object. Start and End position represent the start and end position of the Range you want to get within the document. If you omit the Start parameter, it defaults to 0, which is the first position in the document. If you omit the End parameter, it defaults to the last position in the document.

In the nampspace code, type this.

[sourcecode language=”csharp”]
using System;
using System.Collections.Generic;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using System.Reflection;
using System.Windows.Forms;
[/sourcecode]

Get all Range

To get all range in the document, type the code bellow:

[sourcecode language=”csharp”]
public void sampleCode()
{
object missingValue = System.Reflection.Missing.Value;
Word.Range range = Globals.ThisAddIn.Application.ActiveDocument.Range(ref missingValue, ref missingValue);
MessageBox.Show(String.Format("{0}", range.Text));
}

[/sourcecode]

MessageBox used for output of the code. Beside it, we know Console.WriteLine. But, MessageBox more efficient.

Get selected Range

To get selected Range in the document, we must use Start and End position.

For example:

[sourcecode language=”csharp”]

public void sampleCode()
{
object missingValue = System.Reflection.Missing.Value;
Word.Range range = Globals.ThisAddIn.Application.ActiveDocument.Range(ref missingValue, ref missingValue);

range.Text = "This\nis\na\ntest.";

object startIndex = 0;
object endIndex = 9;

Word.Range range2 = Globals.ThisAddIn.Application.ActiveDocument.Range(ref startIndex, ref endIndex);
range2.Select();
string result = range2.Text;

MessageBox.Show(result.Length.ToString());
MessageBox.Show(range2.Text);
}
[/sourcecode]

output:

This
is
a

In this case, index start position is 0 and index end position is 9. Where:

Index[0,1] = “T”
Index[1,2] = “h”
Index[2,3] = “i”
Index[3,4] = “s”
Index[4,5] = “\n”
Index[5,6] = “i”
Index[6,7] = “s”
Index[7,8] = “\n”
Index[8,9] = “a”

Get a Range from Selection object

Basically, Selection object as known as blocked text in a Office Word. The code to get Range from Selection object:

[sourcecode language=”csharp”]

public void sampleCode()
{
Word.Selection s = Globals.ThisAddIn.Application.Selection;
if (s != null)
{
if (s.Type == Word.WdSelectionType.wdSelectionNormal)
{
Word.Range r = s.Range;
MessageBox.Show(r.Text);
}
}
}
[/sourcecode]

<< BACK

Tinggalkan Balasan