Our next example of a macro function makes use of the CXllFinder class.
Note: the full code for this example can be found in the project FindReplace in the Samples sub-directory.
Create a new function FindReplace() as shown below.
Name: FindReplace
Add the following line near the top of tutorial1.cpp:
CopyC++#include <XllFinder.h>
Amend the generated code as shown below, and build the project.
CopyC++CXlOper* FindReplace_Impl(CXlOper& xloResult)
{
// End of generated code
//}}XLP_SRC
const TCHAR* apszPairs[] = {
_T("Fred"), _T("Freda"),
_T("George"), _T("Georgina"),
0
};
// Iterate through each find/replace task
for (int i = 0; apszPairs[i]; i += 2) {
// Create a finder
CXllFinder finder(apszPairs[i], FALSE, TRUE);
// Alternatively - create a finder for a specific sheet
//CXllFinder finder(apszPairs[i], FALSE, TRUE, _T("FindReplace.xls"), _T("Sheet2"));
// Look for each match
CXlRef xlrFind;
while (finder.FindNext(xlrFind)) {
// Inspect the current value
CXlOper xloValue;
finder.GetCurrentValue(xloValue);
TRACE(_T("%s\n"), (LPCTSTR)xloValue.ToString());
// Change the value in the matched cell
finder.SetCurrentValue(apszPairs[i + 1]);
}
}
return xloResult.Ret();
}
Build the project, and start Excel.
Type the values "George" and "Fred" into several cells.
Using the Alt-F8 key (or with one of the other methods described in the last topic), run the FindReplace macro. Note that each of the Georges and Freds turn to their feminine equivalents.