在VB中创建动态图表宏

时间:2015-06-08 06:43:12

标签: excel vba excel-vba excel-2010 excel-2007

目前我正在尝试设计一个宏,它允许我从多个工作表中选择数据,并根据拾取的值,将它们相互对照。保存该值的单元格在每个其他工作表中都是相同的。

我写了一些关于如何处理这个问题的伪尝试:

Function WorksheetExists(ByVal WorksheetName As String) As Boolean
Dim Sht As Worksheet
Dim Value = "B20" 'The value to chart will be B20 across every chart'
For each Sheet in ThisWorkbook.Worksheets
'This is where I would start referencing the B20 fields and comparing them'

End Function

谢谢!

1 个答案:

答案 0 :(得分:0)

以下代码使用的是另一种方法,它不是从不同的工作表中选择多个单元格,而是将每个工作表中的单元格内容复制到另一个名为" Graph"并选择该范围作为图形源。代码假设" Graph"工作表是工作簿的第一张工作表。这可能不是您问题的完美答案,但您可以进行一些修改以实现目标。

Sub GraphAdd()

Dim sourceRng As Range
Dim sht As Worksheet
Dim graphSht As Worksheet
Dim wb As Workbook
Dim lastRow As Long

Set wb = ActiveWorkbook
Set graphSht = wb.Worksheets("Graph") '<-- Sheet name where you want to draw the chart

i = 1
For Each sht In ActiveWorkbook.Sheets
    graphSht.Cells(i, 1).Value = sht.Range("B20").Value
    i = i + 1
Next

lastRow = graphSht.Range("A" & graphSht.Rows.Count).End(xlUp).Row

    graphSht.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered
    ActiveChart.SetSourceData Source:=graphSht.Range("A2:A" & lastRow)

End Sub