Friday, June 15, 2018

Use VBA to create a chart in Excel

    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    Dim xlWS As Excel.Worksheet

    Set xlWS = xlWB.Sheets(1)
    xlWB.Sheets("Sheet1").Activate

    Dim chartObj As ChartObject
    Set chartObj = xlWS.ChartObjects.Add _
        (Left:=242, Width:=245, Top:=260, Height:=240)
    chartObj.Chart.SetSourceData Source:=xlWB.Sheets("Sheet2").Range("A1:C2")
    chartObj.Chart.ChartType = xl3DPie
    chartObj.Chart.Elevation = 45
    chartObj.Chart.ChartArea.Border.LineStyle = xlDash
    chartObj.Chart.ChartArea.Border.LineStyle = xlNone

    chartObj.Chart.SeriesCollection(1).ApplyDataLabels
    chartObj.Chart.SeriesCollection(1).DataLabels.ShowPercentage = True
    chartObj.Chart.SeriesCollection(1).DataLabels.ShowValue = False
    chartObj.Chart.SeriesCollection(1).DataLabels.ShowCategoryName = True
    chartObj.Chart.SeriesCollection(1).DataLabels.Font.Size = 8
    chartObj.Chart.SeriesCollection(1).DataLabels.Font.Name = "Cambria"
    chartObj.Chart.SeriesCollection(1).DataLabels.Font.Bold = False
    chartObj.Chart.SeriesCollection(1).DataLabels.ShowLegendKey = -1
    chartObj.Chart.SeriesCollection(1).DataLabels.Position = xlLabelPositionBestFit
    chartObj.Chart.SetElement (msoElementLegendNone)

    xlWB.SaveAs (curPath & "\Reports\ReportName.xlsx")

    xlWB.Close
    Set xlWB = Nothing
    Set xlApp = Nothing

No comments:

Post a Comment