2

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

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
4

1 回答 1

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
于 2013-01-30T22:43:46.187 回答