Excel查找单元格名称

我试图写一个简单的方法来查找activecell是否有一个命名的范围,如果是的话,那是什么。 但它不太好。 这是我的代码:

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()); } 

首先添加Microsoft.Office.Interop.Excel参考

在使用部分添加下面的行

 using Excel = Microsoft.Office.Interop.Excel; 

以下是获取活动单元格值的代码

 //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();