views:

37

answers:

3

Dear reader,

I'm working on a project where the user can insert data into a document using fields, document properties and variables. The user also needs to be able to remove the data from the document. So far, I've managed to remove the document property and variable, but I'm not sure how I would go about removing the field (that's already inserted into the document). Note that I need to compare the field to a string, and if it matches; delete it from the doc. Please advise.

Yours sincerely, Kevin

+1  A: 

I'm assuming you're using .NET Interop with Word. In that case, I believe you're looking for Field.Delete.

This is of course also assuming you know how to get the field you're looking for, which would usually be enumerating through _Document.Fields (or a more finite range if you know one) until you get the right one.

lc
Thank you kindly for your response. I'm currently enumerating through all the document fields, but how do I read the field information? For example: {DOCPROPERTY MyField /*Mergeformat*/} How would I be able to get the "MyField" programmatically? I cannot find the right property in my field to compare it to.
Kevin van Zanten
@Kevin van Zanten - Is `Field.Code.Text` what you're looking for?
lc
Yes, that's exactly what I needed, thank you to you as well sir!
Kevin van Zanten
@Kevin van Zanten - Sure thing. Interop can be a bit annoying (and the documentation is rather trial-and-error-ish at times). Sometimes it's just worth setting a breakpoint and playing around with intellisense in the immediate window until you find what you're looking for.
lc
I'll definitely give that a go next time, thank you kindly!
Kevin van Zanten
A: 

The Field has a Delete method. See the documentation for Field.Delete.

So I think something like this would work:

foreach(Field f in ActiveDocument.Fields)
{
    f.Select();
    if(f.Type == TypeYouWantToDelete)
    {
        d.Delete();
    }
}
ho1
A: 

Thank you for answering. This is what I have so far:

foreach (Word.Field f in ActiveDocument.Fields)
{
    if (f.Type == Word.WdFieldType.wdFieldDocProperty))
    {
        // Compare the value of the field to a string
    }
}

As you can see I need to delete a specific DocProperty field with a specific value, and I need to compare it to a string. How would I do that?

Kevin van Zanten
Not sure but I think it's just something like `f.Result.Text`.
ho1
Or if you want to compare with the code rather than the result I suppose it would be `f.Code.Text` or something.
ho1
That did the trick. I didn't know about .Result.Text/.Code.Text Thank you very much.
Kevin van Zanten