Looks like there are a few things that might be causing your code to not work as expected...
1. Incorrect use of SynonymInfo
The SynonymInfo
object in Word's interop API provides synonyms for a given word but does not return a boolean or a direct comparison to check whether a word belongs to a part of speech.
To fix this, check MeaningCount
before accessing synonyms. Instead of trying to compare Selection.Text
directly to SynonymInfo
, you need to check whether SynonymInfo
actually contains meanings.
Try the following:
WordCtDoc = TSearchNumberOfTimes.Text.ToString();
WordCt = 1;
while (WordCt <= WordCtDoc.Length) // Fix: Changed to 'Length' instead of Max()
{
Globals.ThisAddIn.Application.Selection.MoveRight(WdUnits.wdWord, 1, WdMovementType.wdExtend);
string selectedText = Globals.ThisAddIn.Application.Selection.Text.Trim(); // Ensure no extra spaces
var synonymInfo = Globals.ThisAddIn.Application.SynonymInfo[selectedText, WdPartOfSpeech.wdAdjective];
if (synonymInfo.MeaningCount > 0) // Fix: Properly check if the word has meanings
{
Globals.ThisAddIn.Application.Selection.Font.Color = WdColor.wdColorRed;
LBSelectedAdjectives.Items.Add(selectedText);
}
Globals.ThisAddIn.Application.Selection.MoveRight(WdUnits.wdWord, 1, WdMovementType.wdMove);
WordCt++;
}
2. Fixing WordCtDoc.Max()
Your original code uses WordCtDoc.Max()
, which does not seem to make sense in this context. Since WordCtDoc
is a string, calling .Max()
will return the highest character value, not the length of the string.
To fix this, use WordCtDoc.Length
instead.
3. Handling whitespace in selection
Word may include extra spaces or newline characters in Selection.Text
, causing mismatches. Use .Trim()
when accessing the text.
4. Preventing errors if no synonyms exist
If SynonymInfo
does not contain any synonyms, directly accessing it without checking MeaningCount
first can cause an error. The fix is to check synonymInfo.MeaningCount > 0
before proceeding.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin