

NOTE: First line of the range of data will become the Column Names of the Table. Say that this is the created file with name “DB Data.xlsx” Store data in your excel file and save it some location in your system.
#Odbc excel vba how to
To Read about how to use this Data Source for reading the Data Click Here


In this example, the connection string specifies an Open Database Connectivity (ODBC) data source that is a Microsoft Access file named budget.mdb. ♦ A connection string: This describes the type of data source and the filename. The PivotCache object needs the following information to retrieve the data from the external file: In the example in the previous section (which used data in a worksheet database), the SourceType argument was xlDatabase. Notice that the SourceType argument for the Add method of the PivotCaches collection is specified as xlExternal. PivotFields("ACTUAL").Orientation = xlDataField End With End Sub PivotFields("BUDGET").Orientation = xlDataField. PivotFields("DIVISION").Orientation = xlPageField. PivotFields("MONTH").Orientation = xlColumnField. PivotFields("DEPARTMENT").Orientation = xlRowField. TableDestination:=Sheets("PivotSheet").Range("A1"), _ TableName:="BudgetPivot") QueryString = "SELECT * FROM BUDGET" With PTCache Set PTCache = _ (SourceType:=xlExternal)ĭBFile = ThisWorkbook.Path & "\budget.mdb"ĬonString = "ODBC DSN=MS Access Database DBQ=" & DBFile ' Delete PivotSheet if it exists On Error Resume Next Application.DisplayAlerts = False Sheets("PivotSheet").Delete On Error GoTo 0 Sub CreatePivotTableFromDB() Dim PTCache As PivotCache Dim PT As PivotTable Listing 17-3: Generating a Pivot Table from an External Database It assumes that the budget.mdb database file is stored in the same directory as the workbook.
#Odbc excel vba code
The code that creates the pivot table is shown in Listing 17-3. The Access database consists of a single table that is identical to the data used in the previous example. The example in this section demonstrates how to write VBA code to create a pivot table based on data stored in an Access database file. As you probably know, Excel also enables you to use an external data source to create a pivot table. In the preceding example, the source data was in a worksheet.
