此代码不起作用我想在VB6中的Form_Load上创建一个控件数组,因为我必须为拼字游戏板制作225个它们,并且它们必须精确。我的代码是:
Private lblblocks(1 To 225) As Label
Private Sub Form_Load()
Dim i As Integer, j As Integer
For i = 1 To 15
For j = 1 To 15
Dim arrnum As Integer
arrnum = (i - 1) * 15 + j
Load lblblocks(arrnum)
With lblblocks(arrnum)
.Width = 1000
.Height = 1000
.Top = (i - 1) * 1000
.Left = (j - 1) * 1000
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next j
Next i
End Sub
我使用背景颜色来查看我的所有标签框。此代码不起作用。我收到错误“对象变量或未设置块变量”。有帮助吗?我不知道出了什么问题。我想将标签盒保存在一个控制数组中,我知道如何在不将其作为控制数组的情况下进行操作。
答案 0 :(得分:6)
Index
属性值为零。这将创建一个只有一个元素的控制数组,索引为零。然后,您可以修改代码以生成所需的结果,如下所示:
Private Sub Form_Load()
Dim i As Integer
Dim j As Integer
For i = 0 To 14
For j = 0 To 14
Dim tileIdx As Integer
tileIdx = i * 15 + j
'If the tile index is zero, we already have that control,
'so there's no need to load new instance. Otherwise, use the
'Load method to create a new control in the array with the
'specified index.
If tileIdx > 0 Then
Load lblTile(tileIdx)
End If
With lblTile(tileIdx)
.Width = 1000
.Height = 1000
.Top = i * 1000
.Left = j * 1000
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next
Next
End Sub
如注释中所述,您不需要在数组索引零处加载另一个控件实例,因为您在设计时就这样做了。我还从零开始迭代我的数组,以便稍微更轻松地计算索引。
答案 1 :(得分:0)
我们可以从头开始添加
Private Sub Command3_Click()
Dim rownum As Integer, ColNum As Integer
'Dim lblblocks(1 To 225) As Label
Dim lblblocks() As Label
Dim wwidth As Integer, hheight As Integer
wwidth = 400: hheight = 200
Dim i As Integer, j As Integer
rownum = 20: ColNum = 25
ReDim lblblocks(1 To rownum * ColNum)
For i = 1 To rownum
For j = 1 To ColNum
Dim arrnum As Integer
arrnum = (i - 1) * ColNum + j
Set lblblocks(arrnum) = Me.Controls.Add("VB.Label", "LB" & arrnum)
With lblblocks(arrnum)
'Set Bb(i) = formname.Controls.Add("VB.CommandButton", "Bb" & i)
.Width = wwidth
.Height = hheight
'.Top = (i - 1) * 100
'.Left = (j - 1) * 400
.Top = (i) * hheight
.Left = (j) * wwidth
.Caption = arrnum
.Visible = True
.BackColor = Int(Rnd(1) * 255) + &H100 * Int(Rnd(1) * 255) + &H10000 * Int(Rnd(1) * 255)
End With
Next j
Next i
End Sub