使用特定列

时间:2017-12-14 10:30:05

标签: excel-vba charts vba excel

我有一个宏,用于创建一个图表,其中包含“激活”列和“值”列(不带标题)的值 现在,“激活”列是A,“值”列是E,但有时这个位置可能不同 如何将此宏更改为“激活”和“值”的任何位置?

    Sub CreateChart()

    Dim rng As Range
    Dim cht As Object

    Set find1 = Sheet1.Cells(1, 1).EntireRow.Find(What:="Activation", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
    CA = find1.Column 'column number for Activation
    Set find2 = Sheet1.Cells(1, 1).EntireRow.Find(What:="Value", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)
    CV = find2.Column 'column number for Value
    Dim lastRow As Long   
    lastRow = ActiveSheet.Cells(Rows.Count, CA).End(xlUp).Row

    'I want to change the A column with CA and the E column with CV
    Set rng = Range("A2:A" & lastRow & ",E2:E" & lastRow)

    Set cht = ActiveSheet.Shapes.AddChart2  
    cht.Chart.SetSourceData Source:=rng
    cht.Chart.HasTitle = False          
    cht.Chart.ChartType = xlLine
        With ActiveSheet
    .ChartObjects(1).Top = .Range("I2").Top
    .ChartObjects(1).Left = .Range("I2").Left
    .ChartObjects(1).Width = 500
    End With

    End Sub

1 个答案:

答案 0 :(得分:0)

真的?

   set rng = range("a2:" & cells(lastrow,ca).address) & ",E2:" & cells(lastrow,cv).address)

EDIT        set rng = range(Cells(2,ca).address&":"& cells(lastrow,ca).address)& "" &安培;细胞(2,cv)。地址& ":" &安培;细胞(LASTROW,CV)。地址)

EDIT2(对不起,请不要擅长检查我的打字)

set rng = range(Cells(2,ca).address & ":" & cells(lastrow,ca).address & "," & cells(2,cv).address & ":" & cells(lastrow,cv).address)