Excel中的VBA:从ActiveX文本框创建图表

时间:2012-10-03 12:30:05

标签: excel vba excel-vba charts activex

我正在尝试从我放入工作表中的5个ActiveX文本框创建一个图表。首先,用户键入值,然后按下生成图表的按钮。

这是我的方法,但它不起作用。它说的是“必要的对象”

Private Sub CommandButton1_Click()

Dim arKurse(4) As Double

arKurse(0) = Conver.ToDouble(TextBox1.Text)
arKurse(1) = Conver.ToDouble(TextBox2.Text)
arKurse(2) = Conver.ToDouble(TextBox3.Text)
arKurse(3) = Conver.ToDouble(TextBox4.Text)
arKurse(4) = Conver.ToDouble(TextBox5.Text)


Dim oChtObj As ChartObject
Set oChtObj = ActiveSheet.ChartObjects.Add(Left:=445, Width:=385, Top:=10, Height:=245)

With oChtObj.Chart
    .SeriesCollection.NewSeries
    .SeriesCollection.Values = arKurse
    .SeriesCollection.XValues = Array("1", "2", "3", "4", "5")

    .ChartType = xlLine
    .HasLegend = False
    .HasTitle = True
    .ChartTitle.Caption = "Chart"

End With

End Sub

1 个答案:

答案 0 :(得分:2)

有些事情不起作用

  1. 除非您有充分理由使用自定义方法,否则Conver.ToDouble应为CDbl?
  2. TextBox.Text应该是userform上的Textbox.value,并且最好用它的父级来限定文本框的位置。 (在本例中为Userform1,但如果文本框位于工作表上,则可以是Sheet1)
  3. 需要定义哪个seriescollection
  4. 以下内容已更新为希望

    Option Explicit
    
    Sub SetupUserformToTest()
    UserForm1.Show
    UserForm1.TextBox1.Value = 1
    UserForm1.TextBox2.Value = 2
    UserForm1.TextBox3.Value = 3
    UserForm1.TextBox4.Value = 4
    UserForm1.TextBox5.Value = 1
    CommandButton1_Click
    End Sub
    
    Private Sub CommandButton1_Click()
    
    Dim arKurse(4) As Double
    
    arKurse(0) = CDbl(UserForm1.TextBox1.Value)
    arKurse(1) = CDbl(UserForm1.TextBox2.Value)
    arKurse(2) = CDbl(UserForm1.TextBox3.Value)
    arKurse(3) = CDbl(UserForm1.TextBox4.Value)
    arKurse(4) = CDbl(UserForm1.TextBox5.Value)
    
    Dim oChtObj As ChartObject
    Set oChtObj = ActiveSheet.ChartObjects.Add(Left:=445, Width:=385, Top:=10, Height:=245)
    
    With oChtObj.Chart
        .SeriesCollection.NewSeries
        'Assumed series 1
        .SeriesCollection(1).Values = arKurse
        .SeriesCollection(1).XValues = Array("1", "2", "3", "4", "5")
    
        .ChartType = xlLine
        .HasLegend = False
        .HasTitle = True
        .ChartTitle.Caption = "Chart"
    End With
    
    End Sub