Cómo hacer gráficos en Excel desde Visual Basic

Visual Basic para Aplicaciones (VBA) permite, entre otras acciones, crear gráficos en Excel. Si quieres aprender cómo hacer gráficos en Excel desde Visual Basic podrás seguir el siguiente tutorial. Además, crearemos un libro de Excel que contendrá el gráfico insertado en una hoja de cálculo.

Insertar y hacer gráficos en Excel desde Visual Basic

Para incrustar un gráfico en Excel desde Visual Basic podremos seguir los siguientes pasos y obtener un gráfico en Excel:

  • Crear un nuevo proyecto en Visual Basic.
  • Se creará un Form1.
  • Añadir un botón de comando al formulario.
  • En el evento click del comando añadiremos el siguiente código:

Private Sub Command1_Click()

Dim oXL As Object        ‘ Excel application
Dim oBook As Object      ‘ Excel workbook
Dim oSheet As Object     ‘ Excel Worksheet
Dim oChart As Object     ‘ Excel Chart

Dim iRow As Integer      ‘ Index variable for the current Row
Dim iCol As Integer      ‘ Index variable for the current Row

Const cNumCols = 10      ‘ Number of points in each Series
Const cNumRows = 2       ‘ Number of Series

ReDim aTemp(1 To cNumRows, 1 To cNumCols)

‘Insertar Excel y crear un nuevo libro
Set oXL = CreateObject(“Excel.application”)
Set oBook = oXL.Workbooks.Add
Set oSheet = oBook.Worksheets.Item(1)

‘ Insertar datos al azar en las dos series
Randomize Now()
For iRow = 1 To cNumRows
For iCol = 1 To cNumCols
aTemp(iRow, iCol) = Int(Rnd * 50) + 1
Next iCol
Next iRow
oSheet.Range(“A1”).Resize(cNumRows, cNumCols).Value = aTemp

‘Añadir gráfico en la primera hoja del libro
Set oChart = oSheet.ChartObjects.Add(50, 40, 300, 200).Chart
oChart.SetSourceData Source:=oSheet.Range(“A1”).Resize(cNumRows, cNumCols)

‘ Hacer visible Exccel:
oXL.Visible = True

oXL.UserControl = True

End Sub

 

Bibliografía:

  • Microsoft Excel 2016. Ofimática personal. Editorial ENI. ISBN: 978-2-409-00048-5. Consultada Pág. 485 – 489 y Pág 293
  • Introducción a VBA en Office. Support de Office. Consultado online https://docs.microsoft.com/es-es/office/vba/library-reference/concepts/getting-started-with-vba-in-office