1

我正在尝试通过从驱动器中打开 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
4

1 回答 1

4

Dim excelApplication As Microsoft.Office.Interop.Excel.Application = Nothing,excelApplicationNothing...

尝试这个:

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.
于 2012-06-23T06:34:14.450 回答