问题
Add Check Box to UserForms Dynamically through code
I am trying to collect all file names in a specific folder in multiple check boxes in a user form so that i can select one by one to move to another folder....after adding one check box i couldn't add another during run time please help.
Private Sub Download_file_Click()
Dim wrkbk As Workbook
Dim ofs As New FileSystemObject
Dim ofolder As Folder
Dim ofile As File
Dim mars_path As String
Dim chkBox As MSForms.CheckBox
Dim files_count As Integer
Dim i As Integer
Dim sheet_name As String
Dim NewCheckBox As MSForms.CheckBox
Dim file_name As String
Set wrkbk = Application.Workbooks("Download files.xlsm")
mars_path = input_path.Value
If mars_path = "" Then
MsgBox "Please provide input path first!"
Exit Sub
End If
If ofs.FolderExists(mars_path) Then
Set ofolder = ofs.GetFolder(mars_path)
MsgBox "files are present!!"
End If
files_count = ofolder.Files.Count
sub_folder_count = ofolder.SubFolders.Count
MsgBox "# files =" & files_count & "and # folder =" & sub_folder_count
'********folder check***************
i = 1
'Create the User Form
Set myform = wrkbk.VBProject.VBComponents.Add(3)
With myform
.Properties("caption") = "New Form"
End With
For Each ofile In ofolder.Files
file_name = ofile.Name
MsgBox file_name
'Create CheckBox
Set NewCheckBox = myform.designer.Controls.Add("Forms.CheckBox."&i)
With NewCheckBox
.Caption = file_name
End With
i = i + 1
Next ofile
i = 1
For Each SubFolders In ofolder.SubFolders
file_name = SubFolders.Name
MsgBox file_name
'Create CheckBox
Set NewCheckBox = myform.designer.Controls.Add("Forms.CheckBox." & i)
With NewCheckBox
.Caption = file_name
End With
i = i + 1
Next SubFolders
Unload Me
End Sub
回答1:
try this
Set NewCheckBox = myform.Controls.Add("Forms.CheckBox.1", "Check" & i, true) ' first string must be this, 2nd is name, 3rd is visible=true.
you still might want to add the new controls to an array, collection, or dictionary (my prefered, because easier to remove stuff and test if exists).
Hope this helps. Patrick Lepelletier.
edit: "more" help by pressing F1 in VBE on the line Userform1.controls.add , or this link https://msdn.microsoft.com/en-us/library/office/gg251373.aspx
来源:https://stackoverflow.com/questions/41164574/how-to-add-check-boxes-to-a-user-form-dynamically-through-a-loop-in-vba