使用 VBA,如何在传递记录集字段的用户窗体中创建复选框

Using VBA, How to Create CheckBox in a UserForm passing the RecordSet Fields

我有一个命令按钮,它需要动态显示用户表单,如下所示,从记录集中提取的列 Headers 作为复选框选项。

我的初始化代码如下

Private Sub UserForm_Initialize()
    Set xl1 = Excel.Application
    Dim xlXML As Object
    Dim adoRecordset As Object
    Dim rng As Range
    Dim recordCount1 As Long
    Dim Fieldcount1 As Long
    xl1.ThisWorkbook.Sheets(2).Activate
    Set rng = xl1.ThisWorkbook.Sheets(2).Range("A1:I15")
    Set adoRecordset = CreateObject("ADODB.Recordset")
    Set xlXML = CreateObject("MSXML2.DOMDocument")
    xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)
    adoRecordset.Open xlXML
    adoRecordset.MoveFirst
    Fieldcount1 = adoRecordset.Fields.Count
    Dim i As Long
    Dim chkBox As CheckBox
    For i = 1 To Fieldcount1
        Set chkBox = UserForm1.Controls.Add("Forms.Checkbox.1", "Checkbox" & i)
        chkBox.Caption = adoRecordset.Fields(i - 1)
        chkBox.Value = False
        chkBox.Top = (chkBox.Height + Spacing) * (i - 1)
    Next i

End Sub

我收到 "Run-time error '13': Type mismatch" 错误

你能帮我解决这个问题吗?

我是脚本编写的初学者

问题出在变量声明中。您需要:

Dim chkBox As MSForms.CheckBox