none
Saving Excel charts to a spreadshheet RRS feed

  • Question

  • Hi folks,

    I am writing some code to save an Excel chart to a worksheet. The code I wrote doesn't work.

    Any suggestions?

    Thanks.

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
            Dim xlApp As Excel.Application = GetObject(, "Excel.Application")
            Dim xlWB As Excel.Workbook = xlApp.ActiveWorkbook
            Dim xlWS As Excel.Worksheet = xlWB.ActiveSheet
    
            'add data
            xlWS.Cells(1, 1) = ""
            xlWS.Cells(1, 2) = "Student1"
            xlWS.Cells(1, 3) = "Student2"
            xlWS.Cells(1, 4) = "Student3"
    
            xlWS.Cells(2, 1) = "Term1"
            xlWS.Cells(2, 2) = "80"
            xlWS.Cells(2, 3) = "65"
            xlWS.Cells(2, 4) = "45"
    
            xlWS.Cells(3, 1) = "Term2"
            xlWS.Cells(3, 2) = "78"
            xlWS.Cells(3, 3) = "72"
            xlWS.Cells(3, 4) = "60"
    
            xlWS.Cells(4, 1) = "Term3"
            xlWS.Cells(4, 2) = "82"
            xlWS.Cells(4, 3) = "80"
            xlWS.Cells(4, 4) = "65"
    
            xlWS.Cells(5, 1) = "Term4"
            xlWS.Cells(5, 2) = "75"
            xlWS.Cells(5, 3) = "82"
            xlWS.Cells(5, 4) = "68"
    
            ' create Chart
            Dim chartPage As Excel.Chart
            Dim xlCharts As Excel.ChartObjects
            Dim myChart As Excel.ChartObject
            Dim chartRange As Excel.Range
    
            xlCharts = xlWS.ChartObjects
            myChart = xlCharts.Add(10, 80, 300, 250)
            chartPage = myChart.Chart
            chartRange = xlWS.Range("A1", "d5")
            chartPage.SetSourceData(Source:=chartRange)
            chartPage.ChartType = Excel.XlChartType.xlColumnClustered
    
            'xlWS.SaveAs("C:\vbexcel.xlsx")
            'xlWS.Close()
            'xlApp.Quit()
    
            'releaseObject(xlApp)
            'releaseObject(xlWB)
            'releaseObject(xlWS)
    
        End Sub
    


    Bernie

    Friday, March 8, 2019 12:02 AM

All replies

  • Hi Bernie Ok,

    I'm afraid code you provided is insufficient.  When I executed your code, syntax error occurred.
    Could you provide more code in order to open an Excel file and use it?
    Regards,

    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    Friday, March 8, 2019 8:26 AM