Reputation: 1778
I am trying to use C# to select only the text inside a word table cell so that I can right click on the selected text and assign a hyperlink. The problem is that everything I try selects the entire cell and not the text alone. Because a cell is selected, the right-click context menu does not offer me the hyperlink option.
I found some promising VBA code elsewhere on SO, and I’m trying to model it with C#. But nothing works. No matter what I do, the entire cell is always selected.
I put my cursor in the cell and run variations of the code below. What am I doing wrong?
// https://stackoverflow.com/questions/33946827/ms-word-select-text-inside-a-table-cell
// VBA to select characters 4 through 9 in a cell
//itable.Cell(1,2).Range.Characters(4).Select
//Selection.MoveEnd wdCharacter, 5
// C#
var cell = sel.Range.Cells[1];
var text = cell.Range.Text; // to see it in the debugger
cell.Range.Start = cell.Range.Text[0];
cell.Range.End = cell.Range.Text.Length - 3;
cell.Range.Select();
// OR model the VBA code above, but this doesn’t work either
// use -1 for trim \r and -1 for 0-based
//var moveLength = cell.Range.Text.Length - 2;
//sel.MoveEnd(WdUnits.wdCharacter, moveLength);
Upvotes: 0
Views: 1289
Reputation: 4983
The following code will show how to select only the text in a table cell (in a Word document) instead of the entire cell. As a bonus, within the full code, I've included code that shows how to programmatically change the text in the table cell into a hyperlink. However, since that wasn't part of the OP, it's commented out.
Add the following using statement:
using Word = Microsoft.Office.Interop.Word;
Code snippet:
private Word.Application _wordApp = new Word.Application();
private Word.Document _doc = null;
...
public void HighlightCellText(string filename, int tableNum, int row, int col)
{
object oMissing = System.Reflection.Missing.Value;
//set Word visibility
_wordApp.Visible = true;
//open Word document
_doc = _wordApp.Documents.Open(filename, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
_doc.Activate();
//desired table cell
Word.Cell cell = _doc.Tables[tableNum].Cell(row, col);
Word.Range rng = cell.Range;
rng.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1);
rng.Select();
...
}
HelperWord.cs (full code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Office = Microsoft.Office.Interop;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
namespace WordInteropHighlightCellText
{
public class HelperWord : IDisposable
{
//create new instance
private Word.Application _wordApp = new Word.Application();
private Word.Document _doc = null;
public string Filename { get; set; } = string.Empty;
public void Dispose()
{
if (_doc != null && !String.IsNullOrEmpty(Filename))
{
//save document
_doc.SaveAs2(Filename, Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdWord2013);
_doc = null;
}
if (_wordApp != null)
{
//close Word
object oFalse = false;
_wordApp.Quit(ref oFalse, ref oFalse, ref oFalse);
//release all resources
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_wordApp);
_wordApp = null;
}
}
public void HighlightCellText(string filename, int tableNum, int row, int col)
{
string errMsg = string.Empty;
bool isVisible = true;
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
if (!File.Exists(filename))
{
errMsg = String.Format("Filename '{0}' not found.", filename);
throw new Exception(errMsg);
}
//suppress displaying alerts (such as prompting to overwrite existing file)
_wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
//set Word visibility
_wordApp.Visible = isVisible;
//if writing/updating a large amount of data
//disable screen updating by setting value to false
//for better performance.
//re-enable when done writing/updating data, if desired
//_wordApp.ScreenUpdating = false;
//open Word document
_doc = _wordApp.Documents.Open(filename, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, isVisible, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
_doc.Activate();
//desired table cell
Word.Cell cell = _doc.Tables[tableNum].Cell(row, col);
Word.Range rng = cell.Range;
rng.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1);
rng.Select();
//the following code will make the text in the table cell a hyperlink with the specified link address
//convert text to hyperlink
//object linkAddress = "https:\\www.microsoft.com";
//object oRng = cell.Range;
//cell.Range.Hyperlinks.Add(oRng, ref linkAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //works
if (!_wordApp.ScreenUpdating)
{
//in case screen updating was previously disabled,
//enable screen updating by setting value to true
_wordApp.ScreenUpdating = true;
//refresh screen
//_wordApp.ScreenRefresh();
}
if (!String.IsNullOrEmpty(filename))
{
try
{
//save the document
//_doc.SaveAs(filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
_doc.SaveAs2(filename, Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdWord2013);
}//try
catch (Exception ex)
{
errMsg = "Error: WordWriteDocument - " + ex.Message;
System.Diagnostics.Debug.WriteLine(errMsg);
if (ex.Message.StartsWith("Cannot access read-only document"))
{
System.Windows.Forms.MessageBox.Show(ex.Message + "Please close the Word document, before trying again.", "Error - Saving", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
}
}
}
}
Resources:
Upvotes: 1