2017-02-23 56 views
1

我宣布在常规模块公共全局字典对象如下:全球字典对象可访问从一个窗体

Public dicModels As Scripting.Dictionary 'Microsoft Scripting Runtime has been added as a reference 

我有以下的回调:

Sub CreatePPT_OnAction(control As IRibbonControl) 
    Call CurrentBooks 
    Dim frmPPT_Slide As FPowerPoint 
    Set frmPPT_Slide = New FPowerPoint 
    frmPPT_Slide.Show 
    Set frmPPT_Slide = Nothing 
End Sub 

这里是我的子程序呼叫过程:

Sub CurrentBooks() 
    Dim wks As Excel.Worksheet 
    Dim vObject As Variant 

    If Not dicModels Is Nothing Then Exit Sub 

    Set dicModels = New Dictionary 
    For Each wks In ActiveWorkbook.Worksheets 
     For Each vObject In wks.ListObjects 
      If Left(vObject.Name, 3) = "TM_" Then 
      dicModels.Add Key:=vObject.Name, Item:=Right(vObject.Name, Len(vObject.Name) - InStr(1, vObject.Name, "_")) 
      End If 
     Next vObject 
    Next wks 

End Sub 

这是我在用户窗体中的初始化事件(iCounter是一个模块级别变量声明为私人):

Private Sub UserForm_Initialize() 
    Me.Caption = "Main Tracking Model" 
    Me.lblModel.Caption = "Choose a model to be reflected on the PPT slide." 
    For iCounter = 0 To dicModels.Count '<< ERROR!!!!! 
     Me.lstModels.AddItem dicModels.Items(iCounter) 
    Next iCounter 
End Sub 

我想创建一个全局字典对象可以从userform类访问。虽然我已经在模块级声明了它,但我仍然得到Object variable or With block variable not set。我必须误解或忽略某些东西。任何帮助表示赞赏。谢谢!

+0

在' CurrentBooks'你正在使用'Set dicModels = New Dictionary'。代码在这里的问题应该工作,或者至少'dicModels'不应该是'Nothing'。 Colud是发生了一些事情,我们在这里没有看到,哪些是dic。到'没有'?还有一个问题:“UserForm_Initialize”的代码属于“FPowerPoint”的权利? – dee

+0

@dee是的,'UserForm_Initialize'中的代码属于'FPowerPoint'。很显然,有些东西是将dic对象设置为Nothing。否则,我的范围出现问题。我会做更多的调试。 – Brian

回答

1

写如下:

Public dicModels As New Scripting.Dictionary 

这两个声明的变量,并将其初始化为一个新的Dictionary


该初始化可以与声明一起完成。如果初始化更复杂,那么最好不要声明变量public,而应该有一个公共函数返回变量的值,并在需要时执行任何初始化:

Dim m_dicModels As Scripting.Dictionary 

Public Function dicModels() As Scripting.Dictionary 
    If m_dicModels Is Nothing Then 
     Set m_dicModels = New Scripting.Dictionary 
     m_dicModels.CompareMode = TextCompare 
    End If 
    Set dicModels = m_dicModels 
End Function 
+0

谢谢你的解决方案,但我不能得到它的工作。当用户窗体初始化时,我无法访问'dictionary'对象的'count'属性。字典不是“没有”。因此,为什么我不能从userform初始化事件访问其任何成员? – Brian