在我的Excel中我有:
如果“apple”已经存在,我想在“apple”旁边的单元格中写入“It already exists”。
此代码不起作用
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
子例程arrange_duplicates的位置如下:
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
相反,此代码有效:
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
子例程arrange_duplicates的位置如下:
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
我的问题是:为什么?
答案的原因在于两个代码之间的区别:)。
在第一段代码中,您在arrange_duplicates
过程中定义了字典对象,因此它的范围仅对该过程是本地的。一旦代码退出该过程,字典就会被销毁。当再次调用该段代码时,它每次都会创建一个全新的字典对象(因此没有值)。
在第二段代码中,您将字典对象传递给函数,并将其全部传递给函数,字典对象保持完整,因为它在CommandButton1_Click
中被调用。