Tuesday 6 April 2004

Automating Excel with C#

After much hair-pulling because I could not make Excel "work" as it should, I came across this article 328347 - PRB: "Member Not Found" Error Message When You Use a For Each Statement on an Excel Collection with Visual Basic .NET or Visual C# .NET

So that's why I couldn't loop through cells!

This seems to work better:
if (m_Excel.Workbooks.Count >= 1) {

Excel.Sheets sheets = book.Worksheets;
Excel.Range range,cell;
// foreach (Excel.Range cell in range.Cells ) BROKE http://support.microsoft.com/?kbid=328347
foreach (Excel.Worksheet sheet in sheets) {
range = sheet.UsedRange;
for (int row = 1; row <= range.Rows.Count; row++){
for (int col = 1; col <= range.Columns.Count; col++){
cell = (Excel.Range)range.Cells[row, col];
if (null != cell) {
if (null != cell.Value2) {
cellContent = cell.Value2.ToString();
// do something with the text...

Incidentally, I still don't know why ".Value2" ...

No comments:

Post a Comment

Note: only a member of this blog may post a comment.