VBA字典问题

时间:2018-12-05 13:53:18

标签: vba dictionary

我有以下子代码,在运行完整的工作簿时,需要迭代几个子代码。我想做的是创建一个字典,将其写入子目录中,然后再在子目录中访问以获得最大值。如果我在子目录中创建字典,则逐行覆盖该字典,因此无法获得最大值;如果在另一个子目录中创建字典,则写入时会遇到问题。你有什么建议?

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

感谢您的答复,我已对代码进行了修改,但仍使字典覆盖了每一行。我相信这是造成它的原因:-设置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

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ p >

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

2 个答案:

答案 0 :(得分:0)

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

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

Option Explicit
Dim dctCurrent As Dictionary

Private Sub EntryProcToMyLogic()
    Set dctCurrent = New Dictionary

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

End Sub

答案 1 :(得分:0)

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

创建一个返回您的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