0

I am writing an Office Add-In in C#. I am trying to get the number of characters without spaces from a Word document with the WdBuiltInProperty. However, the conversion to long does not work.

The error message is:

The COM Object of Type "System._ComObject" can not be converted to "System.IConvertible"

Here is my code snippet of thisAddIn.cs so far:

using Word = Microsoft.Office.Interop.Word;
// ...
public partial class ThisAddIn
{
  public void Calc()
  {
    Word.Document doc = this.Application.ActiveDocument ;
    long c=doc.BuiltInDocumentProperties[Word.WdBuiltInProperty.wdPropertyCharacters];
    // ^^^ Error ^^^
  }
}

Questions:

  1. How can the conversion be done properly?

and/or

  1. Is there another way to get the number of characters without spaces ?
SQL Police
  • 4,127
  • 1
  • 25
  • 54

2 Answers2

0

Instead of BuiltInDocumentProperties, use Characters which has a Count property.

long c = doc.Characters.Count;

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.characters.count.aspx

EDIT (from a VBA example):

Sub CountChars()
    Dim iCount(57) As Integer
    Dim x As Integer
    Dim iTotal As Integer
    Dim iAsc As Integer

    Application.ScreenUpdating = False
    iTotal = ActiveDocument.Range.Characters.Count

    For x = 1 To iTotal
        iAsc = Asc(ActiveDocument.Range.Characters(x))
        If iAsc >= 65 And iAsc <= 122 Then
        iCount(iAsc - 65) = iCount(iAsc - 65) + 1
        End If
    Next x
    For x = 0 To 57
        Debug.Print x, iCount(x)
    Next x
    Application.ScreenUpdating = True
End Sub
Community
  • 1
  • 1
Morpheus
  • 1,616
  • 1
  • 21
  • 31
  • Sorry, no, this counts **including** spaces, but I need the count **without** spaces. – SQL Police Oct 29 '15 at 17:53
  • 1
    I found this [SO answer](http://stackoverflow.com/a/17126907/3854195) that explains how to count a specific character. You could use it to count the number of spaces and then subtract that from the total, or alternatively, count individual characters as you iterate and exclude from the count if it's a space. – Morpheus Oct 29 '15 at 20:09
  • Thank you for the link! Indeed, if I find no other solution, I will take this approach. Simply looping through the text and counting. – SQL Police Oct 29 '15 at 21:54
0
int c = doc.BuiltInDocumentProperties[Word.WdBuiltInProperty.wdPropertyCharacters].Value;

Result from BuiltInDocumentProperties[] is Office.DocumentProperty (can be found by inspecting the Locals window in the Word VBA editor), and it's default .Value property contains the number.
It works without .Value in VBA, because VBA has different default value assignment (Let), and separate and object reference assignment with Set. Also, Long type in VBA is Int32 in .NET

Slai
  • 22,144
  • 5
  • 45
  • 53