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