首页 > 解决方案 > VBA 字典问题

问题描述

我有以下子程序,在运行完整的工作簿时我会遍历几个子程序。我要做的是创建一个字典,该字典写入子目录,然后在子目录中访问以获得最大值。如果我在子目录中创建字典,它会被逐行覆盖,因此我无法获得最大值,如果我在另一个子目录中创建字典,我会遇到写入问题。你有什么建议?

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 我在哪里可以从 sub 中定义它以阻止它被每一行覆盖?

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

标签: vbadictionary

解决方案


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

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

Option Explicit
Dim dctCurrent As Dictionary

Private Sub EntryProcToMyLogic()
    Set dctCurrent = New Dictionary

    [other functionality to set up call to CalculateCoordinates()]

End Sub

推荐阅读