0

I'm trying to create a macro for every time a data is inserted in the last line of Excel the chart automatically updates the selected range to include all the data present in the sheet but when the program executes an error occurs, can someone help me?

Code:

Public Sub Chart_Update()

Dim k As Long

k = Cells(Rows.Count, "B").End(xlUp).Row

Range("B2:B" & k & ",E2:E" & k & ",I2:I" & k & ",K2:K" & k).Select
ActiveChart.SetSourceData Source:=Range("AC_Offset_Registers!B2:B" & k & ",E2:E" & k & ",I2:I" & k & ", K2:K" & k)

ActiveWorkbook.Close SaveChanges:=True

End Sub

Error:

Error Info

Error Code

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
KhallP
  • 23
  • 6

2 Answers2

0

Change Range("AC_Offset_Registers!B2:B" … into ThisWorkbook.Worksheets("AC_Offset_Registers").Range("B2:B" … and remove the entire line before (you don't need to .Select).

You might benefit from reading How to avoid using Select in Excel VBA.

Also make sure you specify a worksheet for Cells in the same way ThisWorkbook.Worksheets("AC_Offset_Registers").Cells

Public Sub Chart_Update()
    Dim ws As Worksheet    
    Set ws = ThisWorkbook.Worksheets("AC_Offset_Registers")

    Dim k As Long
    k = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    
    ActiveChart.SetSourceData Source:=ws.Range("B2:B" & k & ",E2:E" & k & ",I2:I" & k & ", K2:K" & k)
    
    ThisWorkbook.Close SaveChanges:=True
End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
0

I found that the name of my chart is "Gráfico 2" but when I run the program I get a "Subscript out of range" error, could you tell me if the code below is right?

Public Sub Chart_Update()

Dim ws As Worksheet, ws_2 As Worksheet, k As Long

Set ws = Sheets("AC_Offset_Registers")
Set ws_2 = Sheets("Gráfico")
k = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row

Charts("Gráfico 2").SetSourceData Source:=ws_2.Range("B2:B" & k & ",E2:E" & k & ",I2:I" & k & ",K2:K" & k)

ThisWorkbook.Close SaveChanges:=True

End Sub

KhallP
  • 23
  • 6
  • Please only use your original question to add code. Answers that do not provide a solution will be deleted by the community. • Try `Worksheets("Gráfico").ChartObjects("Gráfico 2").Chart.SetSourceData Source:=ws.Range("B2:B" & k & ",E2:E" & k & ",I2:I" & k & ",K2:K" & k)` – Pᴇʜ Jun 09 '21 at 13:19