需要绘制线图

时间:2012-09-25 07:06:09

标签: excel vba excel-vba

我对EXCEL VBA很新。 请为我提供以下要求的帮助。

要求:需要EXCEL VBA宏来满足以下要求。

列数n个。第一列是文字。所有其他列都是数字。我需要绘制

的折线图
  1. 第1列(X轴)和第2列(Y轴)
  2. 第1列(X轴)和第3列(Y轴)
  3. 。 ñ。第1列(X轴)和第n列(Y轴)
  4. 所以状态是第1列一直是常数。如何通过动态更改列来循环上述状态?。

    如果我没有清楚解释,请告诉我。

1 个答案:

答案 0 :(得分:0)

基本上这是您录制的宏的一般版本,它将循环所有列,所有行。

Sub PlotLineGraph()
    Dim height As Long
    Dim width As Long
    Dim sourceWs As Worksheet
    Dim targetWs As Worksheet
    Dim targetWorksheetName As String
    Dim targetRange As Range

    Dim targetChart As Chart
    Dim chartsPerRow As Long
    Dim chartWidth As Double
    Dim chartHeight As Double

    'customize the parameters
    chartsPerRow = 2
    chartWidth = 300
    chartHeight = 300
    Set sourceWs = Worksheets("Sheet1") ' replace Sheet1 with the sheet name the data is stored ( Case sensitive)
    targetWorksheetName = "Sheet2"   ' the output sheet name
    Set targetWs = Worksheets(targetWorksheetName)

    '--------------------------------------------------------------------------------
    'optional
    'this part deletes all previous shapes on the target worksheet
    For Each Shape In targetWs.Shapes
        Shape.Delete
    Next Shape
    '--------------------------------------------------------------------------------
    With sourceWs
        height = .Cells(.Rows.Count, 1).End(xlUp).Row ' getting height of column A
        width = .Cells(1, .Columns.Count).End(xlToLeft).Column 'getting columns of row 1
        If width > 1 Then
            For j = 2 To width
                targetWs.Activate
                targetWs.Shapes.AddChart.Select
                ActiveChart.ChartType = xlLine
                Set targetChart = ActiveChart
                .Activate
                Set targetRange = Union(.Range(.Cells(1, 1), .Cells(height, 1)), .Range(.Cells(1, j), .Cells(height, j)))
                targetChart.SetSourceData Source:=targetRange
                With targetChart.Parent
                    .height = chartHeight
                    .width = chartWidth
                    .Top = CLng((j - 2) / chartsPerRow) * chartHeight
                    .Left = ((j - 2) Mod chartsPerRow) * chartWidth
                End With
            Next j
        End If
    End With
End Sub