我在从新创建的元素访问信息时遇到一些问题。这是我的代码
Private Sub c1_Click()
Refresh
Timer1.Enabled = Not Timer1.Enabled
If Timer1.Enabled Then
c1.Caption = "Stop"
Else
c1.Caption = "Start"
End If
a = l.X2 - l.X1
choice = a
End Sub
Private Sub Form_Load()
Dim l As Line
Set l = Controls.Add("VB.Line", "l", Me)
With l
.X1 = 2760
.Y1 = 3000
.X2 = 5640
.Y2 = 3000
.Visible = True
.BorderStyle = 1
.BorderWidth = 2
.BorderColor = vbRed
End With
End Sub
当我点击按钮时出现错误:&#34;对象需要&#34;。在表单上我可以看到该行但我无法从另一个子句访问它。问题出在哪里?< / p>
答案 0 :(得分:3)
您的Line
变量l
是Form_Load
程序专用的,超出了范围。
将Dim l As Line
从Form_Load
移到表单代码模块的顶部(在任何方法或函数之外)。这将使其可用于表单上的任何方法或过程:
Dim l As Line
Private Sub c1_Click()
Refresh
Timer1.Enabled = Not Timer1.Enabled
If Timer1.Enabled Then
c1.Caption = "Stop"
Else
c1.Caption = "Start"
End If
a = l.X2 - l.X1
choice = a
End Sub
Private Sub Form_Load()
Set l = Controls.Add("VB.Line", "l", Me)
With l
.X1 = 2760
.Y1 = 3000
.X2 = 5640
.Y2 = 3000
.Visible = True
.BorderStyle = 1
.BorderWidth = 2
.BorderColor = vbRed
End With
End Sub