如何使用表单上的button和工作表上的数据创build带有柱状图的图表

这是我的Excel VBA类的最后一个项目的一部分。 我创build了一个计算器应用程序,它也将公式和结果写入MathResults表单。 我的下一个任务是取得结果,并与他们创build一个图表。 我从下面的代码中得到的问题是下标超出范围设置ws =表(“MathResults”) 。 当我使用它来select要写入数据的工作表时,此代码工作正常。

Private Sub bttnAddChart_Click() 'variables Dim dataRange As Range Dim endRow As Integer Set ws = Sheets("MathResults") 'find the end of the row endRow = ws.Range("A:A").Find(What:="", After:=Range("A1")).Row 'set the data range Set dataRange = ws.Range("B2:B" & endRow) Charts.Add With ActiveChart .ChartType = xlColumnClustered .Legend.Position = xlRight .Axes(xlCategory).MinorTickMark = xlOutside .Axes(xlValue).MinorTickMark = xlOutside End With End Sub 

显然你的工作簿没有名为"MathResults"工作表。 你想要的是创build它,然后使用它。

更改

Set ws = Sheets("MathResults")

成:

 Set ws = Sheets.Add ws.Name = "MathResults" 

更好的是,你可以尝试find工作表并创build它,如果它还没有在那里:

 On Error Resume Next Set ws = Sheets("MathResults") If ws Is Nothing Then ' <~~ the sheet is not there yet, we need to create it Set ws = Sheets.Add ws.Name = "MathResults" End If On Error GoTo 0