Warm tip: This article is reproduced from serverfault.com, please click

Runtime error 9 when trying to create a chart from a different Workbooks' data

发布于 2020-11-27 11:07:37
Private Sub CommandButton1_Click()

Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Workbooks("asd.xlsx")
Set wks = wkb.Worksheets("Sheet1")

Sheets("Sheet1").Shapes.AddChart.Chart.SetSourceData Source:=wks.Range("A1:B98")

End Sub

This is the code I've written to create a simple chart into my current workbook with data from another workbook in the same folder. Even though the relative path is the same the program returns runtime error 9, which says that I'm referencing a non-existent file. I've even tried putting the absolute path into the wkb variable, but doesn't work there as well.

Any help on this? TIA.

Questioner
Roshan Komaravolu
Viewed
0
Roshan Komaravolu 2020-12-01 18:54:34

So, The main reason I was running in to this issue was that Excel needs the other workbook(s) to be open while plotting graphs AND the workbook in which the graph to be plotted as active. So I've modified the code to open the other workbooks, make the one in which I'm plotting the graph active, plot the graph and then close.

target_workbook.xlsm is the workbook in which the graph has to be drawn, and asd.xlsx is workbook which contains the data.

Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range

Workbooks.Open "C:\full_path_to_file\asd.xlsx"
Workbooks("target_workbook.xlsm").Activate

Set wb = Workbooks("asd.xlsx")
Set ws = wb.Worksheets("Sheet ABC")
Set rng = ws.Range("F3:F98,H3:H98")

MsgBox ("Test-1!")
Set chrt = Sheets("Sheet1").ChartObjects.Add(Left:=5, Width:=600, Top:=7, Height:=350)
chrt.Chart.SetSourceData Source:=rng
chrt.Chart.ChartType = xlLine
MsgBox ("test-2")

Workbooks("asd").Close SaveChanges:=False
End Sub