Answered by:
How to write a for-loop to search a range?

Question
-
I'm new to programming actions in Excel so please forgive me if my question sounds simple or stupid.
I'm using VSTO since I already have Visual Studio 2008. I'm also using C# instead of VB. I already have my range named. I guess what I need is to know some of the range properties. I need a way to write a for-loop to go through each row in the ID column and compare that to another column full of IDs too. So basically something like this:1 For (int x = 1; x < firstRange.NumberOfRows; x++) 2 { 3 For(int y = 1; y < secondRange.NumberOfRows; y++) 4 { 5 if(firstRange.NumberOfRows[x].value == second.RangeOfRows[y].value) 6 { 7 firstRange[NumberOfRows[x],NumberOfColumn["Same"]).value = "Same Value"; 8 { 9 } 10 }
I'm not sure if the above pseudo code makes any sense but that's essentially what I'm trying to do.
Any help is much appreciated.Thursday, February 26, 2009 7:12 PM
Answers
-
Hi ,
We could not compare a entire row at one time, instead we need to compare them cell by cell, please refer to following code:
Excel.Worksheet ws;
ws = Application.ActiveSheet as Excel.Worksheet;
Excel ran = ws.get_Range("A1", "D2");
Excel.Range ran2 = ws.get_Range("A4", "D5");
for (int i = 1; i <= ran.Rows.Count; i++)
{
for (int j = 1; j <=ran.Columns.Count; j++)
{
if (((Excel.Range)ran.Cells[i, j]).Value2 == ((Excel.Range)ran2.Cells[i, j]).Value2)
{
}
}
}
Thanks
We have published a VSTO FAQ recently, you can view them from the entry thread http://social.msdn.microsoft.com/Forums/en/vsto/thread/31b1ffbf-117b-4e8f-ad38-71614437df59. If you have any feedbacks or suggestions on this FAQ, please feel free to write us emails to colbertz@microsoft.com.- Proposed as answer by Himanshu Rakibe Wednesday, March 4, 2009 1:11 PM
- Marked as answer by Tim Li Friday, March 6, 2009 2:08 AM
Wednesday, March 4, 2009 7:13 AM
All replies
-
Hi ,
We could not compare a entire row at one time, instead we need to compare them cell by cell, please refer to following code:
Excel.Worksheet ws;
ws = Application.ActiveSheet as Excel.Worksheet;
Excel ran = ws.get_Range("A1", "D2");
Excel.Range ran2 = ws.get_Range("A4", "D5");
for (int i = 1; i <= ran.Rows.Count; i++)
{
for (int j = 1; j <=ran.Columns.Count; j++)
{
if (((Excel.Range)ran.Cells[i, j]).Value2 == ((Excel.Range)ran2.Cells[i, j]).Value2)
{
}
}
}
Thanks
We have published a VSTO FAQ recently, you can view them from the entry thread http://social.msdn.microsoft.com/Forums/en/vsto/thread/31b1ffbf-117b-4e8f-ad38-71614437df59. If you have any feedbacks or suggestions on this FAQ, please feel free to write us emails to colbertz@microsoft.com.- Proposed as answer by Himanshu Rakibe Wednesday, March 4, 2009 1:11 PM
- Marked as answer by Tim Li Friday, March 6, 2009 2:08 AM
Wednesday, March 4, 2009 7:13 AM -
Thanks, that works!Friday, March 6, 2009 6:58 PM