根据用户表格(VBA)中输入的值绘制水平线

时间:2018-08-29 13:58:30

标签: vba excel-vba

我希望命令按钮在现有图表上绘制一条水平线,以使其等于在同一用户窗体中输入的值。

之前也有人问过类似的问题,所以我从他们对代码的回答中得到启发。但这是行不通的。

这是我的代码:

Private Sub CommandButton2_Click()
    Dim d As Double
    d = res
    With ThisWorkbook.Worksheets("Feuil3").ChartObjects("Graphique 2").Chart 
        With ActiveChart.SeriesCollection.NewSeries
            .Values = Array(d, d)
            .ChartType = xlLine
        End With
    End With
End Sub

res是用户输入的值。

这是我的结果(似乎在0而不是res值处画了一条线;它还将我所有的x轴都向右移动了)。

Screenshot

预先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

从第二行ActiveChart中删除With-您从未激活过图表,因此很难知道哪个图表正在接收该新系列。这段代码对我来说很好:

很难说出您要做什么,但是看来您只想要2个数据点。最好向其中添加动态内容,以找出您需要多少个数据点,然后创建要分配给.Values的数组。

Sub Test3()
    Dim d As Double
    d = 5 'just assigning it here
    With ThisWorkbook.Worksheets("Sheet1").ChartObjects("Chart 1").Chart 
        With .SeriesCollection.NewSeries
            .Values = Array(d, d, d, d, d, d, d, d, d, d) '10 data points
            .ChartType = xlLine
        End With
    End With
End Sub

img1

编辑:

Sub Test3()
Dim d As Double
Dim numberofpoints As Long, i As Long
Dim arr As Variant

d = 5 'just assigning it here
numberofpoints = Cells(Rows.Count, 1).End(xlUp).Row - 1
ReDim arr(0 To 0)

For i = 0 To numberofpoints - 1
    arr(i) = d
    If i <> numberofpoints - 1 Then ReDim Preserve arr(0 To i + 1)
Next i

With ThisWorkbook.Worksheets("Sheet1").ChartObjects("Chart 1").Chart
    With .SeriesCollection.NewSeries
        .Values = arr
        .ChartType = xlLine
    End With
End With
End Sub

img2