zzyxz Posted March 3, 2014 at 08:51 PM Report #547437 Posted March 3, 2014 at 08:51 PM Boas, Estou a fazer um programa em vb 2010, e no fim tenciono apresentar 3 charts: dois de barras, para a quantidade e para o stock do produto e um circular, para a margem de lucro.. Acontece é que sou noob nestas andanças e ja ando a algum a tentar dar com os códigos e não consigo nem adicionar varias legendas à mesma serie nem mudar a cor das barras dependendo do valor delas, tipo, verde para o máximo, vermelho para o mínimo.. Esperava que alguém me pudesse elucidar -.- Ja fiz isto.. Private Sub QuantStats_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim max As Integer = main.nVendPicBox(0) Dim min As Integer = main.nVendPicBox(0) For k = 1 To 15 If main.nVendPicBox(k) > max Then max = main.nVendPicBox(k) End If Next For k = 1 To 15 If main.nVendPicBox(k) < min Then min = main.nVendPicBox(k) End If Next For k = 0 To 15 Select main.nVendPicBox(k) Case Is = min 'red' Case Is = max 'green' Case Else 'yellow' End Select QuantChart.Series("Quantidade de Produto").Points.AddXY(main.DesPicBox(k), main.nVendPicBox(k)) Next End Sub
manuel antonio Posted March 6, 2014 at 01:23 AM Report #547685 Posted March 6, 2014 at 01:23 AM (edited) Boa noite. Para o gráfico de barras, desde que tenhas dados gravados na folha, podes tentar adaptar este código. Ele, elabora o grafico em função da seleção de uma checkbox, mas essa parte, tu podes suprimir. Também só grava até um determinado nº de linhas, no entanto, podes alterar isso como pretenderes. Finalmente grava-te o gráfico como imagem e exibe-o num outro Userform. Como já não é necessário na folha de cálculo, para evitar acumulação de gráficos, apaga-o, ficando no entanto disponível como imagem. Eu preciso dele desta forma, agora tu adapta-o às tuas necessidades. '======================================================= '======================== Criando Gráfico COLUNAS: ======== '======================================================= Image1.Picture = Nothing If UserForm_RegistoConsultas.CheckBox16.Value = True Then Dim wkst As Excel.Worksheet Dim lngRow As Long Dim lngLast As Long Dim GraficoCOLUNA As Excel.ChartObject Dim COLUNA As Excel.ChartObject Dim TipoC As Integer, TipoCs As String Set wkst = ThisWorkbook.Sheets("Folha6") Set COLUNA = wkst.ChartObjects.Add(170, 20, 670, 360) lngRow = wkst.Range("A" & Rows.Count).End(xlUp).Row lngLast = wkst.Range("B" & Rows.Count).End(xlUp).Row ' CRIAR GRÁFICO lngLast = 16 If lngRow > 16 Then With COLUNA.Chart .ChartType = xl3DColumnClustered .PlotArea.Select .ChartArea.Select .SetSourceData wkst.Range("A1:B" & lngLast) .HasTitle = True .SeriesCollection(1).ApplyDataLabels Type:=xlValue .SeriesCollection(1).DataLabels.Select .SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(160, 20, 0) ActiveChart.ChartGroups(1).GapWidth = 20 .ChartTitle.Characters.Text = "MOTIVOS MAIS FREQUENTES EM " & wkst.Range("B1") .Axes(xlCategory, xlPrimary).HasTitle = True .Axes(xlCategory, xlPrimary).AxisTitle.Font.Size = 14 .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "MOTIVOS" .Axes(xlCategory, xlPrimary).TickLabels.Font.Bold = msoTrue .Axes(xlCategory, xlPrimary).TickLabels.Font.Size = 14 .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Font.Size = 12 .Axes(xlValue).MajorUnit = 1 .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "NÚMERO DE UTENTES" '----- FAZ RODAR O GRÁFICO SOBRE OS EIXOS ----- wkst.Shapes(COLUNA.Name).Chart.ChartArea.Format.ThreeD.RotationX = -1 wkst.Shapes(COLUNA.Name).Chart.ChartArea.Format.ThreeD.RotationY = -270 End With Else With COLUNA.Chart .ChartType = xl3DColumnClustered .PlotArea.Select .ChartArea.Select .SetSourceData wkst.Range("A1:B" & lngRow) .HasTitle = True .SeriesCollection(1).ApplyDataLabels Type:=xlValue .SeriesCollection(1).DataLabels.Select .SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(160, 20, 0) ActiveChart.ChartGroups(1).GapWidth = 20 .ChartTitle.Characters.Text = "MOTIVOS MAIS FREQUENTES EM " & wkst.Range("B1") .Axes(xlCategory, xlPrimary).HasTitle = True .Axes(xlCategory, xlPrimary).AxisTitle.Font.Size = 14 .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "MOTIVOS" .Axes(xlCategory, xlPrimary).TickLabels.Font.Bold = msoTrue .Axes(xlCategory, xlPrimary).TickLabels.Font.Size = 14 .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Font.Size = 12 .Axes(xlValue).MajorUnit = 1 .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "NÚMERO DE UTENTES" '----- FAZ RODAR O GRÁFICO SOBRE OS EIXOS ----- wkst.Shapes(COLUNA.Name).Chart.ChartArea.Format.ThreeD.RotationX = -1 wkst.Shapes(COLUNA.Name).Chart.ChartArea.Format.ThreeD.RotationY = -270 End With End If Dim GrCOLUNA As String Set GraficoCOLUNA = COLUNA GraficoCOLUNA.Activate ActiveChart.Parent.Width = 670 ActiveChart.Parent.Height = 360 On Error Resume Next 'exporta a imagem do gráfico para a pasta GrCOLUNA = ThisWorkbook.Path & "\GraficoCOLUNA.JPEG" ActiveChart.Export Filename:=GrCOLUNA, filtername:="JPEG" 'carrega grágico Image1.Picture = LoadPicture(GrCOLUNA) 'elimina o gráfico criado COLUNA.Delete End If para o grafico circular, é mais ou menos o mesmo. '======================================================== '======================== Criando Gráfico CIRCULAR: ======== '======================================================== If UserForm_RegistoConsultas.CheckBox17.Value = True Then Image1.Picture = Nothing Dim cho As Excel.ChartObject Dim GraficoCirc As Excel.ChartObject Set wks = ThisWorkbook.Sheets("Folha4") lngRow = wks.Range("A" & Rows.Count).End(xlUp).Row lngLast = wks.Range("B" & Rows.Count).End(xlUp).Row Set cho = wks.ChartObjects.Add(170, 20, 670, 360) lngLast = 11 If lngRow > 11 Then With cho.Chart .ChartType = xl3DPieExploded .PlotArea.Select .SetSourceData wks.Range("A1:B" & lngLast) .SeriesCollection(1).ApplyDataLabels Type:=xlValue .SeriesCollection(1).DataLabels.Select Selection.ShowCategoryName = True Selection.Format.TextFrame2.TextRange.Font.Size = 16 Selection.Format.TextFrame2.TextRange.Font.Bold = msoTrue .SeriesCollection(1).Name = "10 MOTIVOS MAIS FREQUENTES EM " & wks.Range("B1") End With Else With cho.Chart .ChartType = xl3DPieExploded .PlotArea.Select .ChartArea.Select .SetSourceData wks.Range("A1:B" & lngRow) .SeriesCollection(1).ApplyDataLabels Type:=xlValue .SeriesCollection(1).DataLabels.Select Selection.ShowCategoryName = True Selection.Format.TextFrame2.TextRange.Font.Size = 16 Selection.Format.TextFrame2.TextRange.Font.Bold = msoTrue .SeriesCollection(1).Name = "10 MOTIVOS MAIS FREQUENTES EM " & wks.Range("B1") End With End If Dim ArqImagem As String Set GraficoCirc = cho GraficoCirc.Activate ActiveChart.Parent.Width = 670 ActiveChart.Parent.Height = 360 On Error Resume Next '----- FAZ RODAR O GRÁFICO SOBRE EIXO HORIZONTAL ----- wks.Shapes(cho.Name).Chart.ChartArea.Format.ThreeD.RotationY = 50 'exporta a imagem do gráfico para a pasta ArqImagem = ThisWorkbook.Path & "\GraficoCirc.JPEG" ActiveChart.Export Filename:=ArqImagem, filtername:="JPEG" 'carrega gráfico Image1.Picture = LoadPicture(ArqImagem) 'elimina o gráfico criado na folha cho.Delete 'Kill ArqImagem End If Vai por tentativas como eu, que me vi grego para chegar aqui. Se não conseguires ajuda aqui, procura na Net, pois há muito disso à disposição. M.A. Edited March 6, 2014 at 01:30 AM by manuel antonio
zzyxz Posted March 6, 2014 at 09:45 PM Author Report #547801 Posted March 6, 2014 at 09:45 PM Vai por tentativas como eu, que me vi grego para chegar aqui. Se não conseguires ajuda aqui, procura na Net, pois há muito disso à disposição. M.A. Bem, antes de mais OBRIGADO manuel antonio!! 😄 Como não estava a chegar lá, acabei por suprimir essa funcionalidade do gráfico, visto que tenho que entregar o trabalho hoje... Resolvi esse tratamento de dados (apresentação do mais e menos vendidos, mais e menos faturados, produtos em rotura de stock) usando listboxes, adicionando para lá os nomes dos produtos Fica mais fatela, mas como nem demos charts (tivemos uma abordagem básica ao vba 2010).. Mesmo assim, vou apresentar os gráficos, tem sempre outro impacto visual e fica sempre melhor... Fico te mesmo agradecido, ja li o teu código e percebi a maior parte.. como ainda tenho que comentar e fazer os debugs finais, não vai dar para o implementar no trabalho, mas talvez no fim de semana pegue nele e estude-o a fundo Cumps, zzyxz
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now