Excel Find method example using C#/VSTO

Found a good example of finding text or formula values in Excel using C#, can be viewed here.

There is a simple change I would make to the example: the first item found is actually the
last instance of the item in the worksheet being searched, so I used the following –

// If Find doesn’t find anything, rgFound will be null
if (rgFound != null)
{
     // Save the address of the first found item –
    // it will be used in a loop terminating condition.
    sFirstFoundAddress = rgFound.get_Address(
                   true, true, Excel.XlReferenceStyle.xlA1, missing, missing);

   // Continue finding subsequent items using FindNext
    rgFound = ws.Cells.FindNext(rgFound);
    string sAddress = rgFound.get_Address(
                    true, true, Excel.XlReferenceStyle.xlA1, missing, missing);

    // Start a loop that calls FindNext until
   // the first found cell is found again
   while (!sAddress.Equals(sFirstFoundAddress))
   {

         //do something with each found item

   }

//Finally, get the first found cell – which will be
//the most bottom right found cell, and do something with it
r1 = ws.get_Range(sFirstFoundAddress, missing) as Excel.Range;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: