【问题标题】:Adding userform controls during runtime "Object variable or with block variable not set" error在运行时添加用户窗体控件“对象变量或未设置块变量”错误
【发布时间】:2020-07-01 07:28:56
【问题描述】:

我下面的代码给出了一个错误

Set VM = AP.VBProject.VBComponents("ViewManager").Designer.Controls

我查看了许多工作代码的示例,但无法弄清楚我的设置是如何导致错误的。

错误是Run-time error '91': Object variable or With block variable not set

感谢您的帮助。

Private Sub btnAdd_Click()
    Dim View As String
    Dim FField As String
    Dim TField As String
    View = cmbView.Value
    FField = cmbFrmFld.Value
    TField = cmbToFld.Value

    'if it is the first add change one way, if after the first add change another
    If ViewManager.Height = 116 Then
        ViewManager.Height = ViewManager.Height + 64.5
    ElseIf frmViews.Height > 116 Then
        ViewManager.Height = ViewManager.Height + 30
    End If

    Dim AP As Project
    Set AP = ActiveProject
    Dim lbl As MSForms.Label
    Dim VM As Object

    Set VM = AP.VBProject.VBComponents("ViewManager").Designer.Controls
    With VM
        Set lbl = .Add("Forms.Label.1")
    End With

    With lbl
        .Left = 6
        .Top = ViewManager.Height - 32
        .Width = 156
        .Caption = View
    End With
End Sub

【问题讨论】:

    标签: vba ms-project


    【解决方案1】:

    我相信您的问题是您正在使用 VBIDE 表单设计器在加载时将控件添加到 ViewManager 表单,这是不可能的。您可以看到将以下代码添加到您的模块并在鼠标停止的“VM”VBComponent 上添加一个监视(右键单击并添加监视)。您会看到“Designer”属性为“Nothing”,而如果您在未加载表单时运行相同的代码,您将能够访问 Designer 属性及其所有属性。

    Sub CheckVBComponent()
        Dim AP As Project, VM as VBIDE.VBComponent
    
        Set AP = ActiveProject
        'Note also this assumes that you've named your ViewManager correctly in the VBProject
        Set VM = AP.VBProject.VBComponents("ViewManager")
    
        'Add watch here
        Stop
    End Sub
    

    这里的简单解决方法是在运行时将控件直接添加到窗体中,而不使用 VBIDE。例如:

    Sub AddLabeltoMSProject
       Dim frmLbl As MSForms.Label
    
       Set frmLbl = ViewManager.Controls.Add("Forms.Label.1")
    
       With frmLbl
           .Caption = "I really love labels"
           .Top = ViewManager.Height - 32
           .Left = 6
           .Width = 156
       End With
    End Sub
    

    【讨论】:

    • 感谢您的回复。您对未填充 Designer 属性是正确的。我没有得到设计师的属性/方法列表。 'ViewManager' 是一个自定义的用户表单。无论如何,我尝试了您的方法,但出现“找不到方法或数据成员”错误。
    • 对不起,我没有意识到它在用户表单上。我的更新应该可以为您解决问题。
    • 感谢 CubeChase。实际上,我的代码与您以前在这里的代码相似,但是(如果我错了,请纠正我)我认为您的代码每次使用表单时都会将表单返回到初始状态。我希望运行时更改是永久性的,这导致我使用设计器。有关如何使这些更改永久化的任何想法?
    • 不,你是对的,更改不是永久性的,下次加载表单时标签将消失。所以是的,通过代码使表单上的控件永久化的唯一方法是通过 VBE 设计器,但是如果加载了表单,您可能必须将其卸载并删除它并使用新控件从头开始重建它。在 VBA 中不太可行且实际上不稳定。唯一的选择可能是通过使用我的答案,但在项目中存储已添加的控件(及其属性),然后在 ViewManager 初始化并在那里重新加载它们时检查这一点。这有意义吗?
    • 确实如此。我认为这是一个尽可能好的答案。再次感谢。
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 2016-10-07
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多