繁体   English   中英

Excel查找单元名称

[英]Excel Find Cell Name

我正在尝试编写一个简单的方法来查找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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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