简体   繁体   中英

Excel Find Cell Name

I am trying to write a simple method to find whether the activecell has a namedrange if so, what is it. But it isnt going too well. Here is my code:

private void btnH4_Click(object sender, EventArgs e)
{
    if (Globals.ThisWorkbook.Application.ActiveCell.Name == null)
    {
        MessageBox.Show("Nothing");
        return; 
    }
    MessageBox.Show(Globals.ThisWorkbook.Application.ActiveCell.Name.ToString());
}

First add Microsoft.Office.Interop.Excel reference

add the below line in using section

using Excel = Microsoft.Office.Interop.Excel;

Below is the code to get the active cell value

//Create excel application object
Excel.Application excelApp = new Excel.Application();
//Create workbook object
Excel.Workbook workBook = excelApp.Workbooks.Open(@"D:\Sample.xlsx");           
//Get the range of active cell
Excel.Range range = (Excel.Range)excelApp.Application.ActiveCell;
//Get the cell value
object cellValue = range.Value;
MessageBox.Show(cellValue.ToString());
//Get the address of an active cell
MessageBox.Show(range.Address);
//Get the active cell name 
foreach (Excel.Name item in workBook.Names)
{
    //Compare the active cell address with named range address
    if (item.RefersToRange.Cells.get_Address() == range.Address)
        MessageBox.Show(item.Name);
}
//Close the workbook
workBook.Close();
//Quit the excel application
excelApp.Quit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM