簡體   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