VBA字典问题



我有下面的子,在运行完整的工作手册时,我会迭代几个子。我想做的是创建一个字典,在子中写入,然后在子中访问,以获得最大值。如果我在sub中创建字典,它会被逐行覆盖,所以我无法获得最大值,如果我在另一个子中创建字典时,我在写入它时遇到问题。你有什么建议?

Private Sub CalculateCoordinates(sThread, node As IXMLDOMNode)
Dim parent_node As IXMLDOMNode, x As Integer, y As Integer, 
y_max_branch As Integer, nList As IXMLDOMNodeList
Dim StepId As String, strXpath As String
Dim inputer, inputer2, inputer3, inputer4 As String
Dim stry As String
Dim dict As Scripting.Dictionary
set dict = New Scripting.Dictionary
add.dict y , x 
debug.print Application.WorksheetFunction.Max(dict.keys)
Call AddCoordinates(node, x, y)
End Sub

谢谢你的回复,我已经相应地修改了代码,但我仍然会覆盖每一行的字典。我相信这是造成它的原因:-Set dctCurrent=New Dictionary我在哪里可以从子中定义它,以防止它在每一行都被覆盖?

Public dctCurrent As Dictionary
Debug.Print "max ITEM:- "; Application.Max(dctCurrent.Items)
Call EntryProcToMyLogic(x, y)
Call AddCoordinates(node, x, y)
End Sub

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Public Sub EntryProcToMyLogic(x, y)
Set dctCurrent = New Dictionary      
Call CalculateCoordinates()
dctCurrent.Add x, y
Debug.Print "max KEY:- "; Application.Max(dctCurrent.Keys)
Debug.Print "max ITEM:- "; Application.Max(dctCurrent.Items)
End Sub

为了防止覆盖,您可以检查dctCurrent是否在Set dctCurrent = New Dictionary之前创建(如果不是dctCurrent Is Nothing(。

创建一个返回dctCurrent的函数,您不必担心。

Option Explicit 'Top of module
Private dctCurrent As Scripting.Dictionary
Public Function CurrentDict() as Scripting.Dictionary
If dctCurrent Is Nothing Then
Set dctCurrent = New Scripting.Dictionary
End If
Set  CurrentDict = dctCurrent
End Function

现在,您可以使用CurrentDict,而不必知道dctCurrent是否已创建。

Public Sub EntryProcToMyLogic(x, y)
CurrentDict.Add x, y
Debug.Print "max KEY:- "; Application.Max(CurrentDict.Keys)
Debug.Print "max ITEM:- "; Application.Max(CurrentDict.Items)
End Sub

虽然我实际上看不到定义的字典变量,但我怀疑您需要在模块级别声明该变量(可能是Private(,以便该模块中的所有proc都可以引用它。

确保只在模块级别声明变量,并且在入口过程中实际将其设置为新字典。这种方法可以确保您控制它的创建时间。

Option Explicit
Dim dctCurrent As Dictionary
Private Sub EntryProcToMyLogic()
Set dctCurrent = New Dictionary
[other functionality to set up call to CalculateCoordinates()]
End Sub

最新更新