Search code examples
c#excelsearchtextboxverify

c# Search excel sheet and verify if textbox contents match cell


Newbie here looking for help please.

I have this code which works but it only confirms if the textbox text is found.

I have been trying to adapt it to confirm if textbox text matches the excel cell exactly or not when searching the excel sheet. Please help as I am new to this and am getting a bit lost.

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(@"C:\pricefile.xlsx");
        Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets["Sheet1"];
        Excel.Range colRange = xlWorkSheet.Columns["A:A"];
        string searchString = textBox1.Text;
        Excel.Range resultRange = colRange.Find(
            What: searchString,
            LookIn: Excel.XlFindLookIn.xlValues,
            LookAt: Excel.XlLookAt.xlPart,
            SearchOrder: Excel.XlSearchOrder.xlByRows,
            SearchDirection: Excel.XlSearchDirection.xlNext
            );

        if (resultRange is null)
        {
            MessageBox.Show("Did not find " + searchString + " in Price File");
        }
        else
        {
            MessageBox.Show("Found " + searchString + " in Price File");
        }
        xlWorkBook.Close(false);
        xlApp.Quit();
    }

Any help would be wonderful. Thank you.


Solution

  • To get an exact match on the string you need to set the LookAt parameter to Excel.XlLookAt.xlWhole. See: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xllookat(v=office.14).aspx

    There is also a MatchCase parameter if you want to make the search case sensitive (default is insensitive). See: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.find(v=office.14).aspx