简体   繁体   中英

C# Interop get last row with data from a specific column

I'm trying to get the last row with data from a specific column and I'm getting the following error when running my code:

Unable to get the CountA property of the WorksheetFunction class

var xlApp = new Microsoft.Office.Interop.Excel.Application();
var wb = (Excel.Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
var wsConfig = wb.Sheets["Config"];

var usedRows = xlApp.WorksheetFunction.CountA(wsConfig.Columns[9]);

Also tried the following code, but returns:

Exception from HRESULT: 0x800A03EC

var usedRows = wsConfig.Range["I1", wsConfig.Cells[1, wsConfig.Rows.Count]].End(Excel.XlDirection.xlDown).Value;

Example:

Column I
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| |

=> usedRows = 5 because there are 5 rows with data on the column I

The classic method to get the last used row in a column (eg A ) is:

last = Sheets("Sheet1").Range("A" & Sheets("Sheet1").Rows.Count).End(xlUp).Row

Which says 'working from the last available row in the worksheet (changes from version to version) go upwards until you hit a cell with a value - your last row.

You can write this in in your example (for column I ) with:

var usedRows = wsConfig.Range["I" + wsConfig.Rows.Count.ToString()].End(Excel.XlDirection.xlUp).Row;

I know this is a couple of years old but just thought I'd put this here. The accepted answer may require a bit of tweaking, as it didn't quite work for me. So I've modified it to the following:

var usedRows = wsConfig.Range["I" + wsconfig.Rows.Count.ToString()].End[Excel.XlDirection.xlUp]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM