如何找到与当前单元格C#+ Excel相邻的单元格的值

时间:2016-10-25 14:26:15

标签: c# excel

我编写了一个程序,找到一个包含“Customer:”的单元格,程序运行正常。问题是,我希望单元格的值直接在单元格旁边。布局看起来像这样:

__________   _________
|Customer:| | Steve  |
|_________| |________|
|Customer:| | John   |
|_________| |________|
|Customer:| | Frank  |
|_________| |________|

所以在这种情况下我会想要值“史蒂夫”,“约翰”和“弗兰克”。我怎么能这样做?

谢谢,卢克

我的代码:

public void gatherInfo()
    {
        string temp = "";

        Excel.Range currentFind = null;
        Excel.Range firstFind = null;

foreach (Excel.Worksheet sheet in excelWorkbook.Application.Worksheets)
        {
            try
            {
                // access cell within sheet
                Excel.Range excelCell =
                      (Excel.Range)sheet.get_Range("A1", Type.Missing);                   

                currentFind = excelCell.Find("Customer:", Type.Missing,
            Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,
            Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
            Type.Missing, Type.Missing);

                while (currentFind != null)
                {
                    // Keep track of the first range you find. 
                    if (firstFind == null)
                    {
                        firstFind = currentFind;
                    }

                    // If you didn't move to a new range, you are done.
                    else if (currentFind.get_Address(Excel.XlReferenceStyle.xlA1)
                          == firstFind.get_Address(Excel.XlReferenceStyle.xlA1))
                    {
                        //String value of cell
                        temp = currentFind.Value2.ToString();

                        break;
                    }

                    currentFind = excelCell.FindNext(currentFind);

                }

                //Find adjacent cell value here?

                holdInformation.Add(temp);

            }

            catch
            {
                Console.WriteLine("Couldn't get customer name");
            }

1 个答案:

答案 0 :(得分:1)

我认为偏移功能正是您所寻找的。在您的代码中,您可以添加一行:

firstFind.Offset[0, 1]; 

“0”表示您定位当前行 “1”表示您要从excel范围

指向右侧的第1列