“对象引用未设置为对象的实例” - 在Excel中创建数据透视表时

时间:2012-06-23 06:21:10

标签: vb.net excel

我正在尝试通过从驱动器中打开Excel文件来创建数据透视表。

但是我收到的错误是“对象引用没有设置为对象的实例”

我已附上我的代码

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim excelApplication As Microsoft.Office.Interop.Excel.Application = Nothing
        Dim excelWorkBook As Workbook = Nothing
        Dim targetSheet As Worksheet = Nothing
        Dim pivotTable As PivotTable = Nothing
        Dim pivotData As Ranges = Nothing
        Dim pivotDestination As Range = Nothing
        Dim co As PivotField = Nothing
        Dim pivotTableName As String = "Complexity"
        excelApplication.Workbooks.Open("E:\John\ccc.xlsx")
        pivotData = targetSheet.Range("Data!R1C1:R11460C9")
        pivotDestination = targetSheet.Range("Data!R1C11")
        excelWorkBook.PivotTableWizard( _
            XlPivotTableSourceType.xlDatabase, _
            pivotData, pivotDestination, pivotTableName, True, True, _
           True, True, , , False, False, XlOrder.xlDownThenOver, 0)
        With excelApplication.ActiveSheet.PivotTables("Complexity").PivotFields("Com")
        End With
        excelApplication.ActiveSheet.PivotTables("Complexity").AddDataField(excelApplication.ActiveSheet.PivotTables( _
            "Complexity").PivotFields("Per gram"), "Sum of Per gram", XlConsolidationFunction.xlSum)
        excelApplication.ActiveSheet.PivotTables("Complexity").AddDataField(excelApplication.ActiveSheet.PivotTables( _
            "Complexity").PivotFields("Oracle Per gram"), "Sum of Oracle Per gram", XlConsolidationFunction.xlSum)
        excelApplication.ActiveWorkbook.Close()
        excelApplication.Quit()
    End Sub

1 个答案:

答案 0 :(得分:4)

Dim excelApplication As Microsoft.Office.Interop.Excel.Application = NothingexcelApplicationNothing ...

试试这个:

excelApplication = New Microsoft.Office.Interop.Excel.Application`
excelWorkBook = excelApplication.Workbooks.Open("E:\John\ccc.xlsx")
targetSheet = excelWorkBook.Sheets(0) 
' assuming that the sheet you want to work with is the first one.