我认为我在VBA中遇到了一个关于2013年的错误,我想找一个解决方法。在以下示例中,有一个用于创建图形的按钮,以及一个用于向其添加数据的按钮。代码工作正常,直到保存带有图形的文件然后再次加载。然后,CommandButton2_Click()给出错误:“对象chartdata的方法工作簿失败”。
Private Sub CommandButton1_Click()
Dim chartWorksheet As Excel.Worksheet
Dim salesChart As Word.Chart
Set salesChart = ActiveDocument.Shapes.AddChart.Chart
End Sub
Private Sub CommandButton2_Click()
For Each objShape In ActiveDocument.Shapes
If objShape.HasChart Then
With objShape.Chart.ChartData.Workbook.WorkSheets(1)
.ListObjects("Table1").Resize .Range("A1:B10")
For i = 1 To 10
.Cells(i, 1).FormulaR1C1 = CStr(i)
.Cells(i, 2).FormulaR1C1 = CStr(10 * i)
Next
End With
End If
Next
End Sub
代码基于Microsoft's own example,我试图考虑Stack Overflow的一些解决方案,但它们没有解决问题。我希望任何人都可以提供帮助!
答案 0 :(得分:0)
错误不是错误。在使用ChartData之前,必须激活ChartData。否则就会发生坏事。
Private Sub CommandButton1_Click()
Dim chartWorksheet As Excel.Worksheet
Dim salesChart As Word.Chart
Set salesChart = ActiveDocument.Shapes.AddChart.Chart
End Sub
Private Sub CommandButton2_Click()
For Each objShape In ActiveDocument.Shapes
If objShape.HasChart Then
'----------------------------------------- the bugfix ----------------------
objShape.Chart.ChartData.Activate
'---------------------------------------------------------------------------
With objShape.Chart.ChartData.Workbook.WorkSheets(1)
.ListObjects("Table1").Resize .Range("A1:B10")
For i = 1 To 10
.Cells(i, 1).FormulaR1C1 = CStr(i)
.Cells(i, 2).FormulaR1C1 = CStr(10 * i)
Next
End With
End If
Next
End Sub
希望它有所帮助!