Get Cell Value in Excel from Range

后端 未结 1 391
傲寒
傲寒 2021-01-28 23:08

How can I extract the value of a cell from a range object? It seems like it should be simple. This Stackoverflow question and answers did not really help. Here is what I want

相关标签:
1条回答
  • 2021-01-28 23:32

    Most of the problems have already been alluded to, but here is the answer with 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 won't fail. But then you need to test if the string is null or empty before using the value.

    0 讨论(0)
提交回复
热议问题