我正在尝试编写一个简单的方法来查找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());
}
答案 0 :(得分:8)
首先添加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();