How to create charts using Visual basic 2010 to Excel

  • Thread starter Thread starter slowtrem
  • Start date Start date
S

slowtrem

Guest
Hi,

Im stuck creating a chart using VB2010 in excel.

I'm trying to create 2 "xlXYScattercharts " :-

(1) Distance (X-axis) Vs Speed (Y-axis)

(2) distance (X-axis) Vs time(Y-axis)

I managed to export the cells values into excel but i still stuck in getting the charts.

I hope someone could help me out on the codes.

Thank you very much

The Codes as follows:-





Imports System.Data
Imports System.Data.OleDb
Imports excel = Microsoft.Office.Interop.Excel


Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xa As New excel.Application
Dim wb As excel.Workbook
Dim ws As excel.Worksheet
Dim time As Integer
Dim speed As Integer
Dim distance As Integer
Dim n As Integer
Dim gridcount As Integer
Dim RNG As excel.Range

Dim j As Integer

Dim excel As New excel.Application



n = 0
time = 0
speed = 0
distance = 0
gridcount = 0

start:
If n < 5 Then
time = time + 1
speed = speed + 5
distance = distance + 10
n = n + 1
Me.DataGridView1.Rows.Add(time, speed, distance)

GoTo start
Else
GoTo next1

End If



next1:



wb = xa.Workbooks.Add
ws = wb.Worksheets("sheet1")

xa.Visible = True

'Adding header details to excel cells

ws.Cells(2, 2) = DataGridView1.Columns(0).HeaderText
ws.Cells(2, 3) = DataGridView1.Columns(1).HeaderText
ws.Cells(2, 4) = DataGridView1.Columns(2).HeaderText

With ws.Range("A2", "D3")
.Font.Bold = True

End With

' AutoFit columns A:D.
Rng = ws.Range("A1", "D1")
Rng.EntireColumn.AutoFit()



'export datagridview date to excel cells


For i As Integer = 0 To DataGridView1.Rows.Count - 1
For j = 0 To DataGridView1.ColumnCount - 1

ws.Cells(2 + (i + 1), 1 + (j + 1)) = DataGridView1(j, i).Value
ws.Cells(2 + (i + 1), 1 + (j + 1)) = DataGridView1(j, i).Value

Next
Next



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' making charts
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim chartPage As excel.Chart
Dim xlCharts As excel.ChartObjects
Dim Chart As excel.ChartObject
Dim chartRange As excel.Range

xlCharts = ws.ChartObjects
Chart = xlCharts.Add(50, 100, 300, 250)
chartPage = Chart.Chart
chartRange = ws.Range("c3", "d7")
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = excel.XlChartType.xlColumnClustered










ws = Nothing : wb = Nothing : xa = Nothing



End Sub

Continue reading...
 
Back
Top