Este artigo demonstra como criar novos gráficos do Excel 5.0 em tempo de execução a ser exibido no controle do recipiente OLE 2.0 Visual Basic.
O controle de recipiente OLE do Visual Basic pode ser usado para incorporar novos objetos OLE em tempo de execução. Um dos objetos que você pode incorporar é um gráfico do Excel. Ele é basicamente um processo de quatro etapas:
- Para incorporar um novo gráfico no controle OLE, defina a propriedade classe Excel.Chart ou Excel.Chart.5. Ambas as classes (Excel.Chart e Excel.Chart.5) são para gráficos do Excel. Mas Excel.Chart.5 é dependente de versão; ela especifica um objeto do Excel versão 5.0 gráfico.
- Criar o objeto definindo a propriedade Action como OLE_CREATE_EMBED. Isso incorpora um gráfico padrão (Chart1) do Excel para o controle OLE. O gráfico (Chart1) é parte de uma pasta de trabalho padrão (Pasta1) que também contém uma planilha padrão (Plan1) para fornecer dados para o gráfico.
- Definir variáveis de objeto para fazer referência os objetos do Excel que você precise manipular o gráfico por meio de automação OLE. Isso irá tornar seu código menor e mais fácil de entender.
- Chame o método ChartWizard para formatar o gráfico.
Definindo variáveis de objeto para objetos do Excel de referência
O controle OLE fornece a propriedade de objeto para permitir que você se referir ao objeto que você criou. Por exemplo, o código a seguir cria e incorpora um gráfico no controle OLE e, em seguida, define o título:
Const OLE_CREATE_EMBED = 0
Ole1.Class = "Excel.Chart.5"
Ole1.Action = OLE_CREATE_EMBED
Ole1.Object.HasTitle = 1
Ole1.Object.ChartTitle.Caption = "Expenses"
você pode navegar da propriedade do objeto o tempo todo, mas seria complicado. Para tornar mais fácil, você pode definir variáveis de objeto para fazer referência os objetos desejados. Aqui é uma versão modificada do exemplo anterior com variáveis de objeto:
Const OLE_CREATE_EMBED = 0
Dim objChart as Object
Dim objChartTitle as Object
Ole1.Class = "Excel.Chart.5"
Ole1.Action = OLE_CREATE_EMBED
Set objChart = Ole1.Object
Set objChartTitle = Ole1.Object.ChartTitle
objChart.HasTitle = 1
objChartTitle.Caption = "Expenses"
o exemplo mostrado no final deste artigo usa três variáveis de objeto:
- Uma referência ao gráfico.
- Uma referência a planilha.
- Uma referência ao objeto do aplicativo.
Chamando o método ChartWizard para formatar um gráfico
Para formatar um gráfico rapidamente, o Excel fornece o método ChartWizard. Com uma chamada para o método ChartWizard, você pode criar um gráfico em um dos vários formatos predefinidos. O exemplo usa esse método, mas você também pode usar manipulação direto a objetos do gráfico.
Antes de chamar o método ChartWizard, a planilha precisa ser preenchido com os dados apropriados. O exemplo cria dados aleatórios. Na maioria das vezes você estará usando dados mais significativos que você pode manipular com o Excel. No exemplo, a orientação xlRows é usada com 1 linha de rótulos de categoria e uma coluna para rótulos de série. Aqui é um diagrama mostrando como os dados são colocados na planilha:
-----------------------------------------------------------
| | Category 1 Label | Category 2 Label |
-----------------------------------------------------------
| Series 1 Label | Data Value | Data Value |
-----------------------------------------------------------
| Series 2 Label | Data Value | Data Value |
-----------------------------------------------------------
| | | |
depois que os dados (incluindo rótulos) tem sido adicionados à planilha, você passar todo o intervalo para o método ChartWizard juntamente com os outros parâmetros de formatação.
Assistente de gráfico sintaxe, parâmetros e descrições
SINTAXE:
Object.ChartWizard(Source, Gallery, Format, PlotBy, CategoryLabels, SeriesLabels, HasLegend, Title, CategoryTitle, ValueTitle, ExtraTitle)
Parameter Description
-------------- -------------------------------------------------
Object The Chart object.
Source Specifies range that contains source data for the chart.
Gallery Specifies chart type (see constants in example.)
Format Specifies built-in autoformat.
PlotBy Specifies orientation of the data (xlRows or xlColumns.)
CategoryLabels The number of rows or columns containing category labels.
SeriesLabels The number of rows or columns containing series labels.
HasLegend Specifies if chart has a legend.
Title The title text of the chart.
CategoryTitle Category axis title text.
ValueTitle Value axis title text.
ExtraTitle Additional axis title text for some charts.
os parâmetros que são mais importantes para o método ChartWizard são:
- PlotBy
- CategoryLabels
- SeriesLabels
Esses parâmetros ou determinam como os dados vai ser configurado, ou eles são inicializados para ajustar os dados que.
Para determinar os parâmetros de galeria e formatação, convém modificar o exemplo. Além disso, você pode gravar o uso do Assistente de gráfico no Excel e ver quais parâmetros são usados.
Tudo isso fica após chamar o método ChartWizard está fechando as referências de objeto e aplicativo.
Exemplo passo a passo
- Inicie um novo projeto no Visual Basic. O Form1 é criado por padrão.
- Adicione um controle OLE 2.0 para Form1 e escolha o botão Cancelar na caixa de diálogo Inserir objeto.
- Adicione um CommandButton (Command1) ao Form1.
- Coloque o seguinte código no CommandButton evento de clique.
Private Sub cmdPrint_Click()
Me.PrintForm
End Sub
Private Sub cmdQ147803_Click()
' Excel chart constants (ODK 1.0 XLCONST.BAS or MsgBox
' in Excel):
Const xlArea = 1
Const xlBar = 2
Const xlColumn = 3
Const xlLine = 4
Const xlPie = 5
Const xlRadar = -4151
Const xlXYScatter = -4169
Const xlCombination = -4111
Const xl3DArea = -4098
Const xl3DBar = -4099
Const xl3DColumn = -4100
Const xl3DLine = -4101
Const xl3DPie = -4102
Const xl3DSurface = -4103
Const xlDoughnut = -4120
' Excel orientation constants:
Const xlRows = 1
Const xlColumns = 2
Dim objChart As Object 'Object reference to Excel
'Chart
Dim objXL As Object 'Object reference for Excel
App
Dim objSheet As Object 'Object reference to Excel
'Worksheet
Dim iRow As Integer 'Index variable for the
'current Row
Dim iCol As Integer 'Index variable for the
'current Row
Dim cRows As Integer 'Number of rows
Dim cCols As Integer 'Number of Columns
Dim cwSource As String 'Named Range
Static cwGallery(15) As Integer 'Array for Chart types
Static iGallery As Integer 'Index for Chart type array
Dim cwFormat As Integer 'Format of Chart type
Dim cwPlotBy As Integer 'How data is taken from
'Worksheet
Dim cwCategoryLabels As Integer 'Rows/Cols with Catagory
'labels
Dim cwSeriesLabels As Integer 'Rows/Cols with Catagory
'Labels
Dim cwHasLegend As Integer 'Display Legend
Dim cwTitle As String 'Chart Title
Dim cwCategoryTitle As String 'Category Title
Dim cwValueTitle As String 'Value Title
Dim cwExtraTitle As String 'Extra Title for some Charts
'disable this button
cmdQ147803.Enabled = False
' Fill in array with possible Chart types:
cwGallery(1) = xlArea
cwGallery(2) = xlBar
cwGallery(3) = xlColumn
cwGallery(4) = xlLine
cwGallery(5) = xlPie
cwGallery(6) = xlRadar
cwGallery(7) = xlXYScatter
cwGallery(8) = xlCombination
cwGallery(9) = xl3DArea
cwGallery(10) = xl3DBar
cwGallery(11) = xl3DColumn
cwGallery(12) = xl3DLine
cwGallery(13) = xl3DPie
cwGallery(14) = xl3DSurface
cwGallery(15) = xlDoughnut
' Embed a new Excel 5.0 Chart into the OLE control:
OLE1.CreateEmbed "", "Excel.Chart.5"
'BEGIN FIX FOR DIFFERING OBJECT MODELS BETWEEN VERSIONS 7 & 8
' Set object references to Chart, Worksheet, and Application
'objects:
If Left(OLE1.object.Application.Version, 1) = "7" Then
'Excel 95's object model is different from Excel 97's
Set objChart = OLE1.object ' Chart1 default chart
Else 'assume all future excel object models are going to be
'the same
Set objChart = OLE1.object.ActiveChart 'ole1.object is in
'Excel 97 the workbook
End If
Set objSheet = objChart.Parent.Worksheets(1) ' Sheet1 default
' data
Set objXL = objChart.Application
'END FIX
' Set the number of columns and rows used for data:
cCols = 10
cRows = 3
' Create Series Labels on Worksheet:
For iRow = 1 To cRows
objSheet.Cells(iRow + 1, 1).Value = "SL" & iRow
Next
' Create Category Labels on Worksheet:
For iCol = 1 To cCols
objSheet.Cells(1, iCol + 1).Value = "CL" & iCol
Next
'exiting here leaves the default chart drawn with sample data
' Create random data on Worksheet:
Randomize Timer
For iRow = 1 To cRows
For iCol = 1 To cCols
objSheet.Cells(iRow + 1, iCol + 1).Value = _
Int(Rnd * 50) + 1
Next iCol
Next iRow
' Name the Range containing the previously added data:
objSheet.Range(objSheet.Cells(1, 1), objSheet.Cells(cRows + _
1, cCols + 1)).Name = "ChartDataRange"
'objSheet.Range(objSheet.Cells(1, 1), objSheet.Cells(cRows + _
1, cCols + 1)).Clear
' Set the ChartWizard parameters:
cwSource = "ChartDataRange" 'Name of Named Range
iGallery = iGallery Mod 15 + 1 'Iterate through 15 Chart
'types
cwFormat = 1 'Use default format of Chart
'Type
cwPlotBy = xlRows 'Rows = Series orientation
cwCategoryLabels = 1 '1 Row contains Category
'Labels
cwSeriesLabels = 1 '1 Column contains Series
'Labels
cwHasLegend = 1 'Display the Legend
cwTitle = "Embedded Chart" 'Chart Title
cwCategoryTitle = "Categories" 'Category Title
cwValueTitle = "Values" 'Value Title
cwExtraTitle = "Extras" 'Extra Title
' Use the ChartWizard method to fill in the Chart:
objChart.ChartWizard cwSource, cwGallery(iGallery), cwFormat,
cwPlotBy, cwCategoryLabels, cwSeriesLabels, cwHasLegend,
cwTitle,cwCategoryTitle, cwValueTitle, cwExtraTitle
' Shut Down Excel and erase objects:
Set objXL = Nothing
Set objChart = Nothing
Set objSheet = Nothing
'enable this button
cmdQ147803.Enabled = True
End Sub
Private Sub cmdXLView_Click()
OLE1.DoVerb vbOLEOpen
End Sub
- Salve o projeto.
- Execute o programa e clique no botão Command1. O primeiro gráfico deve ser criado.
- Manter clicando no botão Command1 para percorrer os tipos de gráfico Galeria 15 de formato 1.
Anotações
- Para modificar um gráfico no controle OLE, você deve ativar o controle primeiro definir a propriedade verbo como -1 (Editar) e, em seguida, definindo a ação de propriedade para 7 (OLE_ACTIVATE). Em seguida, a propriedade do objeto se referirá a um objeto ativo.
- O exemplo usa o formato 1 com o método ChartWizard. Você pode desejar testar com outros valores.
- Depois de usar o método ChartWizard, você ainda pode usar objetos, métodos e propriedades do objeto gráfico para modificá-lo.
- Os usuários poderão editar o gráfico clicando duas vezes no controle OLE ou clicando o botão direito do mouse e escolha Editar a partir do menu pop-up. Você pode eliminar essa capacidade definindo as propriedades AutoAtivar e AutoVerbMenu do controle OLE.