简体   繁体   中英

Excel, VBA: Scripting.dictionary in subroutine not working

In my Excel I have:

在此处输入图片说明

If "apple" already exists, I want to have "It already exists" written in the cell next to "apple".

This code does not work

Option Explicit

Private Sub CommandButton1_Click()

    Dim i As Integer
    Dim fruit As String

    fruit = "apple"

    For i = 1 To 2

        Call arrange_duplicates(i, fruit) '<------------------

    Next i

End Sub

where the subroutine arrange_duplicates is as follows:

Option Explicit

Sub arrange_duplicates(i As Integer, fruit As String)

    Dim dict As New Scripting.Dictionary 'Add Microsoft Scripting Runtime

    If dict.Exists(fruit) Then

        Cells(i, 2).Value = "It already exists"

    Else

        dict.Add fruit, i

    End If

End Sub

On the contrary, this code works:

Option Explicit

Private Sub CommandButton1_Click()

    Dim dict As New Scripting.Dictionary 'Add Microsoft Scripting Runtime '<-------------
    Dim i As Integer
    Dim fruit As String

    fruit = "apple"

    For i = 1 To 2

        Call arrange_duplicates(i, fruit, dict) '<-----------

    Next i

End Sub

where the subroutine arrange_duplicates is as follows:

Option Explicit

Sub arrange_duplicates(i As Integer, fruit As String, dict as Scripting.Dictionary)

    If dict.Exists(fruit) Then

        Cells(i, 2).Value = "It already exists"

    Else

        dict.Add fruit, i

    End If

End Sub

My question is: why?

The answer to the why is in the difference between the two codes :).

In the first piece of code you are defining the dictionary object inside the arrange_duplicates procedure so it's scope is local to only that procedure . As soon as the code exits that procedure the dictionary is destroyed. When that piece of code is called again it creates a brand new dictionary object each time (and thus has no values).

In the second piece of code you pass the dictionary object to the function and all it to evaluate and the dictionary object stays in tact because it's called in the CommandButton1_Click .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM