从Range获取Excel中的单元格值

时间:2015-09-02 18:19:59

标签: vb.net excel excel-interop

如何从范围对象中提取单元格的值?看起来应该很简单。 This Stackoverflow question and answers并没有真正帮助。这是我想要做的,但每次都在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

为了使其工作,我必须实现此代码:

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

这看起来像是一块垃圾。秘密是什么?

1 个答案:

答案 0 :(得分:1)

大多数问题已经被提到,但这里是代码的答案。

    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

如果单元格为空,则使用aCell.Value2.toString将失败,因为Value2将为Nothing。而是使用不会失败的CStr(aCell.Value2)。但是,在使用该值之前,您需要测试字符串是否为空或空。

相关问题