使用Interop循环遍历Range中的所有单元格

时间:2014-11-19 15:22:35

标签: vb.net interop excel-interop

我想循环遍历范围内的所有单元格。

Dim rngTop, rngAll as Excel.Range
'Set a cell
rngTop = DirectCast(_sheet.Cells(1, 2), Excel.Range)
'Set a range from the Top cell to its last cell in the cells column
rngAll = rngTop.End(Excel.XlDirection.xlDown)

    For Each cell As Excel.Range In rngAll
        If cell.Value2 = "x" Then
            'Do stuff
        End If
    Next

cell.Value带下划线并给出了compil错误,即cell.value2是一个对象,我不能在其上使用运算符(在本例中为=)。谁能帮助我完成这项任务? Value2不应该是一个对象。

我也尝试过:

    Dim cell As Excel.Range = Nothing
    Dim i As Integer
    For i = 1 To rngAll.Rows.Count
        If DirectCast(rngAll.Cells(i, 5), Excel.Range).Value2 = "x" Then
        'Do stuff
        End If
    next i

但遇到与上述相同的问题。

1 个答案:

答案 0 :(得分:1)

我想我有解决方案。这里的问题是vb不知道value2将传递什么类型,因此它提供了一个对象。这就是代码提供无法应用= -Operator的消息的原因。使用

If CStr(cell.value2) = "x" then
...

完美无缺。因此,最好的方法是编写一个函数来检查每种可能类型的valuetype并进行转换。

相关问题