25. Automatización con datos de Excel

Cuando los datos se proporcionan en Excel como se describe en Enlaces de datos de Excel, puedes utilizar las funciones UpdateChart y PresentationFromTemplate para controlar mediante programación utilizando esa información.

Con UpdateChart intercambia la hoja de datos de un gráfico específico con sus datos. Con PresentationFromTemplate utiliza sus datos para crear una nueva presentación basada en una plantilla de PowerPoint con gráficos de think-cell vinculados a rangos de datos en Excel.

La interfaz para ambas funciones está integrada en el modelo de automatización de Office, de manera que puede accederse a ella en cualquier lenguaje en el que se programa Office, como Visual Basic para Aplicaciones o C#.

El punto de entrada a think-cell es el objeto de complemento think-cell. Puede accederse a él por medio de la colección Application.COMAddIns. Las llamadas a think-cell son siempre enlazadas en tiempo de ejecución. Consulte la base de conocimientos de Microsoft siguiente para obtener más información:

http://support.microsoft.com/kb/245115.

Así pues, el tipo de objeto de complemento de think-cell es sencillamente Object, y no debe añadirse ningún tipo de biblioteca ni referencia. No tienen más que adquirir el objeto para poder realizar llamadas:

Dim tcaddin As Object 
Set tcaddin = Application.COMAddIns("thinkcell.addin").Object
25.1
UpdateChart
25.2
PresentationFromTemplate

25.1 UpdateChart

25.1.1 Firma

tcaddin.UpdateChart( _ 
    pres As PowerPoint.Presentation, _ 
    strName As String, _ 
    rgData As Excel.Range, _ 
    bTransposed As Boolean _ 
)

25.1.2 Descripción

Esta función, que se invoca desde Excel, actualiza el gráfico strName en pres con los números que se encuentran en rgData. El intervalo rgData tiene que ser conforme con el diseño descrito en Creación de un gráfico con Excel.

Tenga en cuenta que el objeto de presentación pres también puede emplearse para aludir a un intervalo de diapositivas de una presentación. Para obtener más información, consulte:

http://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/slide-object-powerpoint

El nombre del gráfico strName se comprueba sin distinguir entre mayúsculas y minúsculas. Debe haberse asignado previamente en PowerPoint utilizando el control de propiedad Nombre de UpdateChart como se describe en Introducción a la automatización. El nombre del gráfico debe ser exclusivo en la presentación o intervalo de diapositivas que haya definido pres.

Si el gráfico está vinculado a algún intervalo de datos de Excel, el vínculo se rompe al invocar esta función. Posteriormente, el gráfico no quedará vinculado a ningún intervalo de Excel.

25.1.3 Ejemplo

Para utilizar esta muestra, en la ventana de Excel Visual Basic para Aplicaciones vaya a Herramientas, después vaya a Referencias y añada la Biblioteca de objetos de Microsoft PowerPoint.

' When Option Explicit appears in a file, you must 
' explicitly declare all variables using the Dim 
' or ReDim statements. If you attempt to use an 
' undeclared variable name, an error occurs at 
' compile time. 
' Use Option Explicit to avoid incorrectly typing 
' the name of an existing variable or to avoid 
' confusion in code where the scope of the 
' variable is not clear. If you do not use the 
' Option Explicit statement, all undeclared 
' variables are of Object type. 
' http://msdn.microsoft.com/en-us/ 
' library/y9341s4f%28v=vs.80%29.aspx 
Option Explicit 
 
Sub UpdateChart_Sample() 
 
   ' Get the range containing the new data 
   Dim rng As Excel.Range 
   Set rng = ActiveWorkbook.Sheets("Sheet1").Range("A1:D5") 
 
   ' Get the think-cell add-in object 
   Dim tcaddin As Object 
   Set tcaddin = Application.COMAddIns("thinkcell.addin").Object 
 
   ' Get a PowerPoint instance. Hold on to this 
   ' object as long as you want to access the 
   ' generated presentations. There can only be a 
   ' single PowerPoint instance. If there is no 
   ' PowerPoint running, one will be started. 
   ' Otherwise the existing one is used. 
   Dim ppapp As Object 
   Set ppapp = New PowerPoint.Application 
 
   Dim pres As PowerPoint.Presentation 
 
   ' PowerPoint window visible 
   ' Set pres = ppapp.Presentations.Open( _ 
   '  Filename:="c:\\template.pptx", _
   '  Untitled:=msoTrue) 
 
   ' PowerPoint window invisible 
   Set pres = ppapp.Presentations.Open( _
    Filename:="c:\\template.pptx", _
    Untitled:=msoTrue, _
    WithWindow:=msoFalse)
 
   ' The name "Chart1" must have been 
   ' previously assigned to the chart using 
   ' the control in the floating toolbar. 
   ' The final argument indicates whether 
   ' the data range is transposed or not. 
   Call tcaddin.UpdateChart(pres, "Chart1", rng, False) 
 
   ' Save the updated presentation 
   pres.SaveAs ("c:\\template_updated.pptx") 
   pres.Close 
 
   ppapp.Quit 
End Sub

El siguiente ejemplo muestra cómo utilizar UpdateChart a partir de C#.

using Excel = Microsoft.Office.Interop.Excel; 
using PowerPoint = Microsoft.Office.Interop.PowerPoint; 
using Office = Microsoft.Office.Core; 
// Open the Solution Explorer > right-click the project file > "Add Reference..." button and add he following references: 
// .NET tab > Microsoft.Office.Interop.Excel 12.0.0.0 
// .NET tab > Microsoft.Office.Interop.PowerPoint 12.0.0.0 
// COM tab  > Microsoft Office 14.0 Object Library 
namespace ConsoleApplication_UpdateChart 
{ 
  class Program 
  { 
    static void Main() 
    { 
      Excel.Application xlapp = new Excel.Application(); 
      xlapp.Visible = true; 
 
      Excel.Workbook workbook = xlapp.Workbooks.Add(1); 
      Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; 
      worksheet.Cells[3, 1] = "Series 1"; 
      worksheet.Cells[3, 2] = 1; 
      worksheet.Cells[3, 3] = 2; 
      worksheet.Cells[3, 4] = 3; 
 
      PowerPoint.Application ppapp = new PowerPoint.Application(); 
      PowerPoint.Presentation presentation = 
        ppapp.Presentations.Open("C://template.pptx", Office.MsoTriState.msoFalse, Office.MsoTriState.msoTrue); 
 
      object[] aobjArg = new object[] { (object)presentation, "Chart1", worksheet.get_Range("A1", "D3"), false }; 
 
      Office.COMAddIn comaddin = xlapp.COMAddIns.Item("thinkcell.addin"); 
      object objAddIn = comaddin.Object; 
      objAddIn.GetType().InvokeMember("UpdateChart", System.Reflection.BindingFlags.InvokeMethod, null, objAddIn, aobjArg); 
 
      presentation.SaveAs("C://template_updated.pptx"); 
      presentation.Close(); 
      ppapp.Quit(); 
 
      workbook.Close(false); 
      xlapp.Quit(); 
    } 
  } 
}

25.2 PresentationFromTemplate

25.2.1 Firma

tcaddin.PresentationFromTemplate( _ 
    wb As Excel.Workbook, _ 
    strTemplate As String, _ 
    ppapp As PowerPoint.Application _ 
) As PowerPoint.Presentation

25.2.2 Descripción

Esta función, que se invoca desde Excel, aplica todos los vínculos de datos de wb a la plantilla con el nombre de archivo strTemplate. El resultado es una nueva presentación dentro de la instancia ppapp de PowerPoint.

strTemplate puede ser una ruta de acceso completa o relativa, que se toma respecto a la ubicación del archivo del libro de Excel wb.

Todos los gráficos de strTemplate que están vinculados al libro de Excel wb están actualizados (independientemente de que tengan actualización automática o no). A continuación, los vínculos de datos se rompen para impedir nuevos cambios en esos gráficos.

Los gráficos de strTemplate que están vinculados a libros Excel diferentes de wb no sufren cambios y continúan vinculados, de manera que es posible actualizar los vínculos a partir de varios libros de Excel guardando el resultado de esta función como plantilla nueva y, a continuación, llamando de nuevo esta función con el libro siguiente.

Si desea controlar los colores de los segmentos de un gráfico con el enlace de Excel, puede establecer el esquema de colores en Usar relleno de Excel encima (consulte Combinación de colores). De igual forma, para controlar el formato de número con el vínculo de Excel, defínalo como Usar formato de Excel (consulte Formato de número). Asegúrese de que ha definido el color de fondo y el formato de número de las celdas correspondientes en Excel antes de llamar a PresentationFromTemplate.

25.2.3 Ejemplo

Para utilizar esta muestra, en la ventana de Excel Visual Basic para Aplicaciones vaya a Herramientas, después vaya a Referencias y añada la Biblioteca de objetos de Microsoft PowerPoint.

' When Option Explicit appears in a file, you must 
' explicitly declare all variables using the Dim 
' or ReDim statements. If you attempt to use an 
' undeclared variable name, an error occurs at 
' compile time. 
' Use Option Explicit to avoid incorrectly typing 
' the name of an existing variable or to avoid 
' confusion in code where the scope of the 
' variable is not clear. If you do not use the 
' Option Explicit statement, all undeclared 
' variables are of Object type. 
' http://msdn.microsoft.com/en-us/ 
' library/y9341s4f%28v=vs.80%29.aspx 
Option Explicit 
 
Sub PresentationFromTemplate_Sample() 
   ' Get the range to modify. It is more efficient 
   ' to do this once rather than within the loop. 
   Dim rng As Excel.Range 
   Set rng = ActiveWorkbook.Sheets("Sheet1").Cells(3, 2) 
 
   ' Get the think-cell add-in object 
   Dim tcaddin As Object 
   Set tcaddin = Application.COMAddIns("thinkcell.addin").Object 
 
   ' Get a PowerPoint instance. Hold on to this 
   ' object as long as you want to access the 
   ' generated presentations. There can only be a 
   ' single PowerPoint instance. If there is no 
   ' PowerPoint running, one will be started. 
   ' Otherwise the existing one is used. 
   Dim ppapp As Object 
   Set ppapp = New PowerPoint.Application 
 
   Dim i As Integer 
   For i = 1 To 10 
      ' Modify the range value. 
      ' Note: Avoid selecting the cell prior to 
      ' changing it. It is very slow and has 
      ' undesirable side-effects. 
      ' BAD: 
      ' rng.Select 
      ' ActiveWindow.Selection.Value = 0 
      rng.Value = i 
 
      ' Generate a new presentation based on the 
      ' linked template. 
      Dim pres As PowerPoint.Presentation 
      Set pres = tcaddin.PresentationFromTemplate( _ 
       Excel.ActiveWorkbook, "template.pptx", ppapp) 
 
      ' If you want to modify the new presentation 
      ' before saving it this is the place to do it. 
 
      ' Save the new presentation 
      pres.SaveAs "c:\\output" & i & ".pptx" 
 
      ' Explicitly close the presentation when we 
      ' are done with it to free its memory. 
      ' Letting the object go out of scope is not 
      ' sufficient. 
      pres.Close 
   Next 
End Sub

Compartir