How to find column id by cell value?

∥☆過路亽.° 提交于 2019-12-10 14:54:35

问题


I have a huge excel file and would like to find column "ID" for later use. Row 1 is empty, header rows is in the second.

int ID_Number = ((Range)sheet.get_Range("A2", sheet.UsedRange.Columns.Count).Find("ID Number", Missing.Value, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByColumns, XlSearchDirection.xlNext, true, Missing.Value, Missing.Value) ).Column;
int Size = ((Range)sheet.get_Range("A2", sheet.UsedRange.Columns.Count).Find("Size", Missing.Value, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByColumns, XlSearchDirection.xlNext, true, Missing.Value, Missing.Value) ).Column;

Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A03EC

Sometimes the columns order is changing in the excel and would like to handle it dinamically and not by defining column M eg for Size.


回答1:


Is this what you are trying? (TRIED AND TESTED in VS 2010 + Excel 2010)

object misValue = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.get_Range("A2", "A2");

Microsoft.Office.Interop.Excel.Range xlFound = xlRange.EntireRow.Find("ID Number",
misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByColumns, Excel.XlSearchDirection.xlNext, 
true, misValue, misValue);

//~~> Check if a range was returned
if (!(xlFound == null))
{
    int ID_Number = xlFound.Column;
    MessageBox.Show(ID_Number.ToString());
}


来源:https://stackoverflow.com/questions/19973982/how-to-find-column-id-by-cell-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!