Question

What is the correct use of the COMPARE statement in MS Word. I tried the following:

{SET FOO "foo" }
{COMPARE FOO "foo" }
{COMPARE { REF FOO } "foo" }    
{COMPARE { FOO } "foo" }
{COMPARE FOO "Bar" }
{COMPARE { REF FOO } "Bar" }    
{COMPARE { FOO } "Bar" }

If I switch off the field view (Alt-F9), I get:

0
0
0
0
0
0

I would expect that there is at least one "1". How can I achieve this?

Was it helpful?

Solution

{ COMPARE FOO = "foo" }

i.e. the basic syntax is

{ COMPARE comparand1 comparison-operator comparand2 }

But then you need to be a little bit careful. How things are compared depends on the type of comparand and the precise syntax. e.g.

{ SET foo "abc" }
{ COMPARE { foo } = "abc" } returns 1

{ SET foo "abc" }
{ SET abc "def" }
{ COMPARE { foo } = "abc" } returns 0

So { foo } is not treated quite the same as the bookmark "foo"

In this case you can avoid the problem by using the bookmark name alone, as before, i.e.

{ COMPARE foo = "abc" } returns 1

But if the comparand comes in from soemwhere else, e.g. you are comparing a { MERGEFIELD } field, then if the result of the MERGEFIELD is "foo" then this on its own

{ COMPARE { MERGEFIELD myfield } = "abc" } returns 0

but in this case

{ SET foo "abc" }
{ COMPARE { MERGEFIELD myfield } = "abc" } returns 1

In order to ensure that Word does not do an additional "dereference" you have to quote the comparand, i.e.

{ SET foo "abc" }
{ COMPARE "{ MERGEFIELD myfield }" = "abc" } returns 0

Word also converts/coerces texts that start with numbers into numbers in some circumstances, e.g.

{ SET foo "1abc" }
{ SET bar "1bcd" }
{ COMPARE foo = bar } returns 1

{ SET foo "1abc" }
{ SET bar "2bcd" }
{ COMPARE foo = bar } returns 0

So in that case, you would need

{ COMPARE "{ foo }" = "{ bar }" }

or

{ COMPARE "{ REF foo }" = "{ REF bar }" }

to get the comparison you probably expect.

Finally, the spaces around the comparison operator are significant. Even with no bookmark called xyz,

{ COMPARE xyz="abc" } returns 1
{ COMPARE xyz= "abc" } returns 1, but as you might hope
{ COMPARE xyz ="abc" } returns 0 and
{ COMPARE xyz = "abc" } returns 0

OTHER TIPS

You need an operator (e.g. =) in the middle:

{ COMPARE FOO = "foo" }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top