vba 将标签动态添加到用户表单 = 空白用户表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10544456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:07:09  来源:igfitidea点击:

Dynamically Adding Labels to User Form = Blank UserForm

excelvbaexcel-vba

提问by BiGXERO

I'm trying to dynamically add buttons to the userform, but the userform just comes up blank. Ive simplified the essence of the code as much as possible for error checking (not that it's helped me)

我正在尝试向用户表单动态添加按钮,但用户表单只是空白。我已经尽可能地简化了代码的本质以进行错误检查(并不是说它对我有帮助)

Sub addLabel()
UserForm2.Show    
Dim theLabel As Label
Dim labelCounter As Integer

For labelCounter = 1 To 3
    Set Label = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)
    With theLabel
        .Caption = "Test" & labelCounter
        .Left = 10
        .Width = 50
        .Top = 10
    End With
End Sub

Is there any way of checking if the buttons have been added but are invisible? Or why they are not being added. Any help greatly appreciated.

有没有办法检查按钮是否已添加但不可见?或者为什么没有添加它们。非常感谢任何帮助。

回答by brettdj

A few things:

一些东西:

  1. You need to show your UserForm as vbModeless- else the code stops on UserForm2.Show
  2. You are creating an object called Labelthen using Withon theLabel
  3. You will then need to increment the position of your three labels to avoid overlap (which I have done using Top).

    Sub addLabel()
    UserForm2.Show vbModeless
    Dim theLabel As Object
    Dim labelCounter As Long
    
    For labelCounter = 1 To 3
        Set theLabel = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)
        With theLabel
            .Caption = "Test" & labelCounter
            .Left = 10
            .Width = 50
            .Top = 10 * labelCounter
        End With
    Next
    End Sub
    
  1. 您需要将您的用户窗体显示为vbModeless- 否则代码会停止UserForm2.Show
  2. 您正在创建一个名为对象Label,然后使用WiththeLabel
  3. 然后,您需要增加三个标签的位置以避免重叠(我已经使用Top)。

    Sub addLabel()
    UserForm2.Show vbModeless
    Dim theLabel As Object
    Dim labelCounter As Long
    
    For labelCounter = 1 To 3
        Set theLabel = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)
        With theLabel
            .Caption = "Test" & labelCounter
            .Left = 10
            .Width = 50
            .Top = 10 * labelCounter
        End With
    Next
    End Sub
    

回答by user13563126

After the end withstatement, add:

end with语句后添加:

userform1.show

One more correction:

再更正:

.top = 10*labelcounter+10

回答by user3967253

try below code

试试下面的代码

Set theLabel = UserForm2.Designer.Controls.Add("Forms.Label.1", "Test1", True)