5

此代码不起作用我想在 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

我使用背景色来查看我所有的标签框。此代码不起作用。我收到错误“对象变量或未设置块变量”。有什么帮助吗?我不知道出了什么问题。我想将标签框保存在控件数组中,我知道如何在不使其成为控件数组的情况下做到这一点。

4

2 回答 2

6

科迪·格雷在他的评论中说得对。我不相信您只能在 VB6 中的代码中动态创建控件数组。您必须在窗体上放置一个控件实例并将其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

正如评论中所指出的,您不需要在数组索引零处加载控件的另一个实例,因为您在设计时已经这样做了。我还从零开始迭代我的数组,以便更轻松地计算索引。

于 2013-04-17T01:20:50.260 回答
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
于 2018-05-13T16:56:54.147 回答