AJIT JENA

AJIT JENA

  • NA
  • 1
  • 3.2k

Creating Pivot Table in Excel using Dynamic Range VB.Net

Sep 12 2013 4:07 AM
 Hi All,
I wrote a small code in VB.Net to do a Pivot table in excel, it is opening a existing excel file with data in sheet1 and creating a Pivot in sheet2. The code is working fine. My question is can I have a dynamic range I mean all data in sheet1 as range to create pivot table.

Private Sub Button1_Click(ByVal Sender As System.object, ByVal e As System.eventsArgs) handlesButton.Click)
Dim OExcel As Object
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel.Visible = True
oBook = oExcel.Workbooks.Open("D:\Test.xlsx")
Osheet = Obook.Sheets("Sheet1")

Here I wanted to create a dynamic range like ....All data in sheet1
Dim xlRange As Excel.Range = CType(oSheet, Excel.Worksheet).Range("A2:V2000")


oSheet.Name = "Pivot"
Dim xlRange2 As Excel.Range = Ctype(oSheet, Excel.Worksheet).Range("A1")
Dim ptField As Excel.PivotFiled = ptTable.PivotFileds("Total")
with ptField
.Orientation = Excel.xlPivotFieldOrientation.xlDataField
.Function = Excel.xlconsolidataionFunction.xlSum
.Name = "Sum of Tatal"
ptFiled = ptTable.PivotFields("Bank AC Number")
with ptField
.Orientation = Excel.xlPivotFieldOrientation.xlRowField
End With
ptFiled = ptTable.PivotFileds("OFFC Code")
With ptField
.Orientation = Excel.XlPivotFiledOrientation.xlRowField
End With
For Each pt In oSheet.PivotTables
For Each pf In pt.PivotFields
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
Next pt
Osheet.pivotTables("Pivot").PivotFileds("Bank AC Number").RepeatLables = True
Osheet.pivotTables("Pivot").PivotFileds("OFFC Code").RepeatLables = True
End With
End Sub
End Class


Please help me on the dynamic range.


Answers (1)