[英]How to find the value of a cell adjacent to the current cell C# + Excel
I have written a program that finds a cell containing "Customer:" and the program works successfully. 我编写了一个程序,该程序找到包含“ Customer:”的单元格,并且该程序可以成功运行。 The problem is, I want the value of the cell directly next to the cell. 问题是,我希望该单元格的值紧邻该单元格。 The layout looks something like this: 布局看起来像这样:
__________ _________
|Customer:| | Steve |
|_________| |________|
|Customer:| | John |
|_________| |________|
|Customer:| | Frank |
|_________| |________|
So in this case I would want the values "Steve", "John", and "Frank". 因此,在这种情况下,我需要使用值“ Steve”,“ John”和“ Frank”。 How can I do this? 我怎样才能做到这一点?
Thanks, Luke 谢谢,卢克
My Code: 我的代码:
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");
}
i think the offset function is what you are looking for. 我认为偏移量功能就是您想要的。 On your code, you could add a line that goes: 在代码上,您可以添加一行:
firstFind.Offset[0, 1];
"0" to signify that you target the current row "1" to signify that you want to target the 1st column on the right from the excel range “ 0”表示您要定位当前行“ 1”表示您要定位excel范围右侧的第1列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.