Get cell value in Excel from range

How can I extract a cell value from a range object? It seems like it should be simple. This question and the answers to this question did not help. Here is what I want to do, but it fails every time with an exception in row.columns (0,0).

Dim rdr = oFindings.Range For Each row As Excel.Range In rdr.Rows Dim Account = row.Columns(0,0).value2.tostring ' Do other stuff Next 

To do this, I had to implement this code:

 For Each row As Excel.Range In rdr.Rows ndx = 0 For Each cell As Excel.Range In row.Columns If ndx = 0 Then Account = NS(cell.Value2) ' Do other stuff ndx += 1 next Next 

It looks like such a coolge. What's the secret?

0
source share
1 answer

Most of the problems have already been mentioned, but here is the answer with the code.

  Dim rdr As Excel.Range = oFindings.Range For Each row As Excel.Range In rdr.Rows 'explicitly get the first cell as a range Dim aCell As Excel.Range = row.Cells(1, 1) 'explicity convert the value to String but don't use .String Dim Account as string = CStr(aCell.Value2) If Not String.IsNullOrEmpty(Account) Then ' Do other stuff End If Next 

Using aCell.Value2.toString will fail if the cell is empty, because Value2 will be Nothing . Instead, use CStr(aCell.Value2) , which will not fail. But then you need to check if the string is empty or empty before using the value.

0
source

Source: https://habr.com/ru/post/1306684/


All Articles