VBA:使用userform之外的字典

时间:2017-02-01 20:32:06

标签: vba excel-vba excel

我是vba的新手,所以我可能错过了一些东西。

我正在填写模块子中的字典DicOption。 这是子:

Public Sub ExchangeToDicOption()

Static DicOption As Object
Dim LR As Long
Dim Rg As Range
Dim ws As Worksheet
Dim i As Long
Set ws = ActiveWorkbook.Worksheets(2)
Set Rg = ws.Columns(2)

If Not DicOption Is Nothing Then
    DicOption.RemoveAll
End If


    LR = Rg.Find(What:="*", Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False).Row

    Set DicOption = CreateObject("Scripting.Dictionary")

    If LR > 1 Then
        For i = 2 To LR
            DicOption.Add key:=Cells(i, 1).Value, Item:=Cells(i, 2).Value
        Next i
    End If

End Sub

但是字典在完成其进程时似乎自动为空。我在UserForm_Initialize中调用了子ExchangeToDicOption。 Creation_step是DicOption中的一个关键字。

Private Sub UserForm_Initialize()
Dim control As control
Dim opt As String

Call ExchangeToDicOption

opt = DicOption(Creation_step)
With UBidStatus
    Select Case opt
        Case Is > 0
            For Each control In UBidStatus.Controls
                control.Enabled = False
            Next control
            With UBidStatus
                .Image4.Enabled = True
                .LProject.Enabled = True
                .LClient.Enabled = True
                .Label6.Enabled = True
                .Label7.Enabled = True
                .IProjectinfoNOK.Enabled = True
                .IProjectinfoOK.Enabled = True
                .LProjectinfo.Enabled = True
                .CBProjectinfo.Enabled = True
                .IProjectinfoNOK.Visible = True
                .IProjectinfoOK.Visible = False
            End With
ect....

我还尝试使用Public DicOption as Object作为全局变量(在模块编辑窗口中的所有子项之前),但它也不起作用。 谢谢你的帮助!!

1 个答案:

答案 0 :(得分:2)

Public Sub ExchangeToDicOption()

Static DicOption As Object

DicOption对象变量位于本地范围 - 它只存在于ExchangeToDicOption过程中。

UserForm_Initialize中的这一行:

opt = DicOption(Creation_step)

看起来它正在尝试访问在另一个范围内声明的变量。 它不能。

在模块顶部指定Option Explicit;该表单停止编译。或者,如果模块范围内有另一个DicOption变量(在模块顶部,在过程上方声明),那么DicOptionExchangeToDicOption的本地变量} 隐藏它(VBA将对DicOption的调用解析为本地声明,而不是模块级声明)。删除Static DicOption As Object声明。

由于您有两个需要访问同一对象的过程,因此需要在模块级别声明该对象。

Option Explicit
Private DicOption As Object

Private Sub UserForm_Initialize()
    Set DicOption = CreateObject("Scripting.Dictionary")
End Sub

Private Sub UserForm_Terminate()
    Set DicOption = Nothing
End Sub

Public Sub ExchangeToDicOption()
    DicOption.RemoveAll
    LR = Rg.Find(What:="*", Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, MatchCase:=False).Row

    If LR > 1 Then
        For i = 2 To LR
            DicOption.Add key:=Cells(i, 1).Value, Item:=Cells(i, 2).Value
        Next i
    End If
End Sub

现在,不知道为什么你迟到绑定到自1998年以来在任何Windows机器上标准安装的库...但这是另一个问题。

通过初始化UserForm_Initialize中的实例并在UserForm_Terminate中将其终止,您确保在UserForm对象实例的整个生命周期内都有一个非空对象引用。 / p>