Hi,
I have a code that creates pie chart from Access in Excel. But my only problem is to set the Legend label. On legend it shows 1, 2 instead of appropriate labels.
The code:
'sSource is the table name or query that you pass
Public Sub CreatePieChart(sSource As String, msFileName As String)
Dim xlApp As Excel.Application
Dim xlWrkbk As Excel.Workbook
Dim xlChartObj As Excel.Chart
Dim xlSourceRange As Excel.Range
Dim XValuesRange As Excel.Range
Const cINITIALDATA As Integer = 2
Const cTIMESTAMPCOL As Integer = 1
'Export Data
'msFullPath is the path and the name of your excel file
If Dir(msFullPath) <> "" Then
Kill msFullPath
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel97, sSource, msFullPath, False
'Open Excel sheet
Set xlApp = CreateObject("Excel.Application"

Set xlWrkbk = xlApp.Workbooks.Open(msFullPath)
'format data
Set xlSourceRange = xlWrkbk.Worksheets(1).Range("a1"

.CurrentRegion
xlSourceRange.AutoFormat xlRangeAutoFormatClassic3
'get the range
iUsed = xlWrkbk.Worksheets(1).UsedRange.Rows.Count
iCol = xlWrkbk.Worksheets(1).UsedRange.Columns.Count
'set range
Set xlSourceRange = xlWrkbk.Worksheets(1).Range(xlWrkbk.Worksheets(1).Cells(cINITIALDATA, iCol - 1), _
xlWrkbk.Worksheets(1).Cells(iUsed, iCol))
Set XValuesRange = xlWrkbk.Worksheets(1).Range(xlWrkbk.Worksheets(1).Cells(cINITIALDATA, cTIMESTAMPCOL), _
xlWrkbk.Worksheets(1).Cells(iUsed, cTIMESTAMPCOL))
' Create a new chart.
Set xlChartObj = xlApp.Charts.Add
' Format the chart.
With xlChartObj
' Specify chart type as Pie.
.ChartType = xlPie
' Set the range of the chart.
.SetSourceData Source:=xlSourceRange, PlotBy:=xlRows
' Specify that the chart is located on a new sheet.
.Location WHERE:=xlLocationAsNewSheet
' Create and set the title; set title font.
.HasTitle = True
With .ChartTitle
.Characters.Text = "Duplicate Names of Access Application" '& vbCrLf
.Font.Size = cFONTSIZE
.Font.Bold = True
End With
.ApplyDataLabels xlDataLabelsShowPercent
'format legend
.HasLegend = True
.Legend.Position = xlLegendPositionRight
'fill area format
.ChartArea.Fill.Visible = True
'plot area format
.PlotArea.Fill.Visible = True
End With
exit_Here:
On Error Resume Next
' Save and close the workbook
' and quit Microsoft Excel.
With xlWrkbk
.Save
.Close
End With
xlApp.Quit
Set xlSourceRange = Nothing
Set xlChartObj = Nothing
Set xlWrkbk = Nothing
Set xlApp = Nothing
Exit Sub
End Sub