事件处理程序中无法识别的变量

时间:2010-08-11 11:57:10

标签: vba excel-vba excel

在事件处理程序(单击)中,我无法让程序识别变量j(它是本地的)。 当它到达check.Value = MyCheck & j.Value行时,它只返回'Mycheck1',即使它处于循环中。

我需要程序通过所有检查按钮并检查它们是否被选中。 有人知道正确的语法吗?

主要分:

With TempForm.CodeModule
    ' ** Add/change next 5 lines' This code adds the commands/event handlers
    ' to the form
    X = .CountOfLines
    .InsertLines X + 1, "Sub CommandButton1_Click()"
    .InsertLines X + 2, "Dim rs As ADODB.Recordset"
    .InsertLines X + 3, "Dim rst As ADODB.Recordset"
    .InsertLines X + 4, "Dim i As Integer"
    .InsertLines X + 5, "Dim ran as string"
    .InsertLines X + 6, "j = 1 "
    .InsertLines X + 7, "set rs = Rsfun"
    .InsertLines X + 8, "Do While Not rs.EOF"
    '.InsertLines X + 8, "For j = " & i & " To rs.MaxRecords"
    '.InsertLines X + 9, "" & i & " = " & i & " +1"
    .InsertLines X + 9, "Dim check As MSForms.CheckBox "
    .InsertLines X + 10, "Set check = UserForm1.Controls.Add(""Forms.checkbox.1"")"
    .InsertLines X + 11, "check = MyCheck & j"
    .InsertLines X + 12, "If Check.value = true then"
    .InsertLines X + 13, "ran = ""A" & i & ""
    .InsertLines X + 14, "MsgBox (ran)"
    .InsertLines X + 15, "range(ran).value= rs.Fields(0)"
    .InsertLines X + 16, "End If"
    .InsertLines X + 17, "RS.MoveNext"
    .InsertLines X + 18, "j= j+1"
    .InsertLines X + 19, "Loop"
    .InsertLines X + 20, "Unload Me"
    .InsertLines X + 21, "End Sub"
    End With

事件处理程序:

    Sub CommandButton1_Click()
    Dim rs As ADODB.Recordset
    Dim rst As ADODB.Recordset
    Dim j As Integer
    Dim ran As String
    j = 1
    Set rs = Rsfun
    Do While Not rs.EOF
    Dim check As MSForms.CheckBox
    Set check = UserForm1.Controls.Add("Forms.checkbox.1")
    check.Value = MyCheck & j.Value
    If check.Value = True Then
    ran = "A1"
    MsgBox (ran)
    range(ran).Value = rs.Fields(0)
    End If
    j = j + 1
    rs.MoveNext
    Loop
    Unload Me
    End Sub

1 个答案:

答案 0 :(得分:0)

而不是check.Value = MyCheck & j.Value你需要

check.Value = UserForm1.Controls(MyCheck & j).Value

另一件事:

Set check = UserForm1.Controls.Add("Forms.checkbox.1")

将你的cb添加到左上角,下一个将覆盖前一个。 也许在添加之后你想要移动它只是有点像 check.top = j * 15

祝你好运。