如何在VBA中将项目从单元格设置为列末尾

时间:2015-08-28 15:46:17

标签: excel vba excel-vba

我正在尝试更改我的图表上的y-min和y-max值,并确保强制显示所有刻度标签。有关如何使用此代码执行此操作的任何建议吗?

我遇到的问题是使用“Range(”R2:R“& LastRow)的传统方法。选择”因为使用“set”运算符而无效。

Sub MakeFinanceChart()

    Dim rX1 As Range rY1 As Range, rX2 As Range, rY2 As Range, _
        rX3 As Range, rY3 As Range, rX4 As Range, rY4 As Range, _
        rX5 As Range, rY5 As Range, rX6 As Range, rY6 As Range
    Dim rChartPos As Range
    Dim chtO As ChartObject

    Set rX1 = Worksheets("Finance").Range("C5:C" & LastRow).Select 
    Set rY1 = Worksheets("Finance").Range("F5:F80")
    Set rX2 = Worksheets("Finance").Range("C5:C80")
    Set rY2 = Worksheets("Finance").Range("J5:J80")
    Set rX3 = Worksheets("Finance").Range("C5:C80")
    Set rY3 = Worksheets("Finance").Range("L5:L80")
    Set rX4 = Worksheets("Finance").Range("C5:C80")
    Set rY4 = Worksheets("Finance").Range("P5:P80")
    Set rX5 = Worksheets("Finance").Range("C5:C80")
    Set rY5 = Worksheets("Finance").Range("T5:T80")
    Set rX6 = Worksheets("Finance").Range("C5:C80")
    Set rY6 = Worksheets("Finance").Range("X5:X80")

    ' location and dimensions of the chart
    Set rChartPos = Worksheets("PLOTS").Range("O2:X28")
    With rChartPos
        Set chtO = .Parent.ChartObjects.Add(.Left, .Top, .Width, .Height)
        chtO.Name = "Finance Plots"
    End With

    'Plot the Whole Finance CHART
    With chtO.Chart

        .ChartType = xlXYScatterLines

        ' First series
        With .SeriesCollection.NewSeries
            .XValues = rX1
            .Values = rY1
            .Name = "A"
        End With

        ' Second series
        With .SeriesCollection.NewSeries
            .XValues = rX2
            .Values = rY2
            .Name = "B"
        End With

        ' Third series
        With .SeriesCollection.NewSeries
            .XValues = rX3
            .Values = rY3
            .Name = "C"
        End With

        ' Fourth series
        With .SeriesCollection.NewSeries
            .XValues = rX4
            .Values = rY4
            .Name = "D"
        End With

        ' Fifth series
        With .SeriesCollection.NewSeries
            .XValues = rX5
            .Values = rY5
            .Name = "E"
        End With

        ' Sixth Series
        With .SeriesCollection.NewSeries
            .XValues = rX6
            .Values = rY6
            .Name = "F"
        End With

        .SetElement (msoElementChartTitleAboveChart)
        .ChartTitle.Text = "Finance Plot"

    End With

End Sub

1 个答案:

答案 0 :(得分:0)

首先,调暗并为LastRow指定一个值,因为此变量在未指定的情况下使用。

'Find the last row of column C
Dim LastRow as Long
LastRow = Worksheets("Finance").Cells(65000, 3).End(xlUp).Row

然后删除.Select,因为它不需要。

Set rX1 = Worksheets("Finance").Range("C5:C" & LastRow)