VBA图表活动单元格

时间:2018-06-27 18:31:05

标签: excel vba

我在尝试找出如何从单独工作表上的活动单元格创建vba图表时遇到麻烦。本质上,我想做的是从工作表1上的活动单元格创建vba图表,所有信息都驻留在名为“ Tester”的工作表上,所以说我在Sheet1上单击单元格$ C12,然后vba代码将创建图表基于$ C12取决于“测试器”上的信息。然后,我希望该图表目标位于名为Analysis的工作表中。到目前为止,这是我的代码:

Sub createchart()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("tester")


ws.Activate
    ActiveSheet.Shapes.AddChart2(251, xlBarClustered).Select
   ActiveChart.SetSourceData Source:=ws.Range("E" & ActiveCell.Row & ",G" & ActiveCell.Row & ",H" & ActiveCell.Row)
ActiveChart.FullSeriesCollection(1).XValues = "=tester!$E$9,tester!$G$9,tester!$H$9"
    ActiveChart.SetElement (msoElementDataLabelOutSideEnd)
    ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
    ActiveChart.Axes(xlValue).MajorGridlines.Format.Line.Visible = msoFalse
    ActiveChart.FullSeriesCollection(1).DataLabels.ShowCategoryName = False

With ActiveChart
    .HasTitle = True
    .ChartTitle.Characters.Text = "Analysis for " & ws.Range("C" & ActiveCell.Row)
    ActiveChart.HasAxis(xlValue) = False
    ActiveChart.HasLegend = False
End With

End Sub

1 个答案:

答案 0 :(得分:1)

您非常接近实现目标,您的代码唯一的问题是它引用了活动工作表的活动单元格,在您的情况下是工作表“测试器”。

您需要做的是使用一个变量从sheet1获取行引用,然后将其传递给创建图表的代码:

Sub createchart()

Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("tester")
Dim CellRow As Integer    ' create a variable to hold the cell row

wb.Sheets("Sheet1").Select   ' select "sheet1" before we get the active cell row
CellRow = ActiveCell.Row   ' get the row number from the active cell in "sheet1"


ws.Activate
    ActiveSheet.Shapes.AddChart2(251, xlBarClustered).Select

   'Change the code from ActiveCell.Row to our new variable CellRow
   ActiveChart.SetSourceData Source:=ws.Range("E" & CellRow & ",G" & CellRow & ",H" & CellRow)
ActiveChart.FullSeriesCollection(1).XValues = "=tester!$E$9,tester!$G$9,tester!$H$9"
    ActiveChart.SetElement (msoElementDataLabelOutSideEnd)
    ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
    ActiveChart.Axes(xlValue).MajorGridlines.Format.Line.Visible = msoFalse
    ActiveChart.FullSeriesCollection(1).DataLabels.ShowCategoryName = False

With ActiveChart
    .HasTitle = True
    .ChartTitle.Characters.Text = "Analysis for " & ws.Range("C" & ActiveCell.Row)
    ActiveChart.HasAxis(xlValue) = False
    ActiveChart.HasLegend = False
End With

End Sub