我在常规模块中声明了一个公共全局字典对象,如下所示:
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
这是我在Userform中的初始化事件(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 :(得分: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