我在excel 2007中有一张表,我想得到一张图表

时间:2014-04-04 12:20:53

标签: excel vba

我在Excel 2007中有一张表,我想得到一张图表 这是我的代码:

Range("A2:P15").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'list'!$A$2:$P$15")
ActiveChart.ChartType = xlLineStacked
ActiveChart.SetSourceData

表的开头是" A2" 但每次结束都不一样
我无法找到解决方案,所以请帮帮我 谢谢;)

1 个答案:

答案 0 :(得分:1)

如果要从特定起点选择工作表中的所有单元格(在下面的代码中设置为A2),那么我通常会使用LastRow和LastCol函数。获取最后一行/列有很多种不同的方法,我已经包含了我通常使用的内容。

我还添加了您的代码并将其放在名为Main的过程中。这将遍历工作簿中的每个工作表并获取上述范围,然后进入您发布的代码。由于我的工作表中没有数据,我无法测试图表本身的代码:

Sub main()
    Const cStartCell As String = "A2"
    Dim vLastRow As Long, vLastCol As String
    Dim vRange As Range
    Dim vSheet As Worksheet

    For Each vSheet In Application.ActiveWorkbook.Sheets
        vLastRow = LastRow(vSheet.Name)
        vLastCol = LastCol(vSheet.Name)
        Set vRange = vSheet.Range(cStartCell & ":" & vLastCol & vLastRow)
        Debug.Print "Sheet " & vSheet.Name & ", vRange set to address range: " & vRange.Address()

        vSheet.Shapes.AddChart.Select
        ActiveChart.SetSourceData Source:=Range(vRange)
        ActiveChart.ChartType = xlLineStacked
        ActiveChart.SetSourceData (vRange)
    Next vSheet
End Sub

Function LastRow(pSheet As String)
On Error GoTo LastRow_err

    LastRow = Sheets(pSheet).UsedRange.Rows.Count

LastRow_exit:
    Exit Function

LastRow_err:
    Debug.Print "Error in LastRow function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description

End Function

Function LastCol(pSheet As String)
On Error GoTo LastCol_err

    LastCol = ColNoToLetter(Sheets(pSheet).UsedRange.Columns.Count)

LastCol_exit:
    Exit Function

LastCol_err:
    Debug.Print "Error in LastCol function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description

End Function

Function ColNoToLetter(pColNo As Integer)
On Error GoTo ColNoToLetter_err
' Goes from currently active cell and finds the next available row

    ' Local constants / variables
    Const cProcName = "ColNoToLetter"
    Dim vNumberOne As Integer
    Dim vNumberTwo As Integer
    Dim vLetterOne As String
    Dim vLetterTwo As String

    vNumberOne = 0
    vNumberTwo = 0
    vLetterOne = Empty
    vLetterTwo = Empty

    vNumberOne = Int((pColNo - 1) / 26)
    vNumberTwo = pColNo - (vNumberOne * 26)
    vLetterTwo = Chr(vNumberTwo + 64)

    If vNumberOne >= 1 Then
        vLetterOne = Chr(vNumberOne + 64)
    End If

    ColNoToLetter = vLetterOne & vLetterTwo

ColNoToLetter_exit:
    Exit Function

ColNoToLetter_err:
    Debug.Print "Error in ColNoToLetter function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description
    Resume Next

End Function

如果您对代码的工作方式有任何疑问,请与我们联系。