我是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
作为全局变量(在模块编辑窗口中的所有子项之前),但它也不起作用。
谢谢你的帮助!!
答案 0 :(得分:2)
Public Sub ExchangeToDicOption()
Static DicOption As Object
DicOption
对象变量位于本地范围 - 它只存在于ExchangeToDicOption
过程中。
UserForm_Initialize
中的这一行:
opt = DicOption(Creation_step)
看起来它正在尝试访问在另一个范围内声明的变量。 它不能。
在模块顶部指定Option Explicit
;该表单停止编译。或者,如果模块范围内有另一个DicOption
变量(在模块顶部,在过程上方声明),那么DicOption
是ExchangeToDicOption
的本地变量} 隐藏它(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>