Select Range by string
How I can change this feature so I select the range of characters in a word document between the characters "E" and "F", if I have; xasdasdEcdscasdcFvfvsdfv is underli开发者_开发百科ned to me the range -> cdscasdc
private void Rango()
{
Word.Range rng;
Word.Document document = this.Application.ActiveDocument;
object startLocation = "E";
object endLocation = "F";
// Supply a Start and End value for the Range.
rng = document.Range(ref startLocation, ref endLocation);
// Select the Range.
rng.Select();
}
This function will not let me pass by reference two objects of string type.......
Thanks
You need to pass the position in the document you want the range to cover, see: How to: Define and Select Ranges in Documents
I have added some example code below:
var word = new Microsoft.Office.Interop.Word.Application();
string document = null;
using (OpenFileDialog dia = new OpenFileDialog())
{
dia.Filter = "MS Word (*.docx)|*.docx";
if (dia.ShowDialog() == DialogResult.OK)
{
document = dia.FileName;
}
}
if (document != null)
{
Document doc = word.Documents.Open(document, ReadOnly: false, Visible: true);
doc.Activate();
string text = doc.Content.Text;
int start = text.IndexOf('E') + 1;
int end = text.IndexOf('F');
if (start >= 0 && end >= 0 && end > start)
{
Range range = doc.Range(Start: start, End: end);
range.Select();
}
}
Do not forget to close the document and Word etc.
精彩评论