使用Microsoft.Office.Interops.Excel COM

时间:2015-04-30 22:14:11

标签: vb.net excel parsing com

我一直在尝试将变量提供给Microsoft.Office.Interop.Excel.Worksheet.Cells来电,但事实证明它非常挑剔。

我是在一个循环中执行此操作,并且我想将rowcount合并到单元格中进行解析,如下所示:

有这个:

Dim rng As Excel.Range = CType(worksheet.Cells(1, 1), Excel.Range)

想要这个:

Dim rowCount As Integer = 1
Dim rng As Excel.Range = CType(worksheet.Cells(i, 1), Excel.Range)
                                              ^^

但我得到了这个例外:

 System.NullReferenceException: Object reference not set to an instance of an object.

并在调试器中单步执行我的局部变量,我收到了rng.Value的这条悲伤消息:

In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.

我正在解释这意味着需要明确设置单元格范围索引(就像实际放入....Cells(1,1) )一样。

我正在努力实现的目标是什么?如果没有,当我循环遍历excel应用程序的行时,如何动态解析此单元格?

完整代码:

 Dim app As New Excel.Application
            Dim workbook As Excel.Workbook
            Dim worksheet As Excel.Worksheet
            Dim rowCount As Integer = 0
            Dim range As Excel.Range

            workbook = app.Workbooks.Open(specsheetName, [ReadOnly]:=False)
            worksheet = workbook.Worksheets("Sheet1")
            range = worksheet.UsedRange

            updateStatusLabel.Text = range.Rows.Count.ToString() & ", " & range.Columns.Count.ToString()
            Dim i As Integer
            For i = 1 To range.Rows.Count
                Dim msg As String
                Dim Obj As Excel.Range = CType(worksheet.Cells(i, 1), Excel.Range) '<--BREAKS HERE!

                If Obj.Value.ToString.Contains("Device Prefix") Then
                    msg = worksheet.Range("B1").Value().ToString()
                    updateStatusLabel.Text = msg
                    Return '***** adding this is what did it.
                Else
                    updateStatusLabel.Text = "not found"
                End If

                rowCount = rowCount + 1
            Next
            app.Workbooks.Close()

同样,代码运行分配.Cells(1,1)但不代表.Cells(i,1)(微妙差异)

提前致谢!

更新:找到解决方案

*我能够在“updateStatusLabel.Text = msg”之后添加Return(即在找到要解析的单元格之后,一切都运行良好。我想我只是没用过到VB循环系统。我不明白为什么会有效。请参阅上面的代码进行更改。

0 个答案:

没有答案