The xlCoerce function can be used for two different purposes: getting values from cells and converting XLOPERs from one type to another. Although these tasks seem unrelated, they are implemented in the same way.
To understand xlCoerce, consider how Microsoft Excel itself uses this function. Microsoft Excel is polymorphic, allowing a user to pass any type of value to a function; but a function may not understand the data type being passed to it. For example, the SIN function requires a number. The user may enter =SIN("25") in a cell, passing a string argument. Although the user has provided a string, Microsoft Excel knows that the function requires a number, so it uses xlCoerce to coerce the string into a number. The xlCoerce function takes two arguments: an XLOPER to coerce and the target type.
The following example shows how to create a string "25" and coerce it to a number:
XLOPER xStr, xNum, xDestType;
/* Create the string "25" */
xStr.xltype = xltypeStr;
xStr.val.str = "\002" "25";
/* Create the second parameter (xltypeNum) */
xDestType.xltype = xltypeInt; /* xDestType is an integer */
xDestType.val.w = xltypeNum; /* Destination is a number */
Excel4(xlCoerce, &xNum, 2, (LPXLOPER) &xStr, (LPXLOPER) &xDestType);
You can specify more than one target type. Some functions behave differently based on whether an argument is a string or a number. This is called function overloading. For example, the DELETE.MENU function can take a string or a number as its second argument. To cover this possibility, xlCoerce allows you to specify multiple target types.
The following example converts the unknown XLOPER x into a string or a number:
XLOPER xDestType, xStrOrNum;
xDestType.xltype = xltypeInt; /* xDestType is an integer */
xDestType.val.w = xltypeStr | xltypeNum; /* String or number */
Excel4(xlCoerce, &xStrOrNum, 2, (LPXLOPER) &x, (LPXLOPER) &xDestType);