我有以下工作的VBA代码。它列出了新列中序列中缺失的数字,但我现在不知道代码是如何工作的。我不理解For循环和scripting.dictionary。
Const rng As String = "$a$2:$a$218"
Dim d As Object, a, c()
Dim i As Long, mx As Long, mn As Long
Set d = CreateObject("scripting.dictionary")
a = Range(rng)
mx = Application.Max(a): mn = Application.Min(a)
ReDim c(1 To mx - mn + 1, 1 To 1)
For i = 1 To UBound(a): d(a(i, 1)) = 1: Next i
For i = mn To mx
If d(i) <> 1 Then k = k + 1: c(k, 1) = i
Next i
Range("d2").Resize(k) = c
有人可以帮助我吗?
答案 0 :(得分:5)
这看起来会告诉你Dictionary
对象:
http://www.snb-vba.eu/VBA_Dictionary_en.html
您还可以在此处查看文档:
http://msdn.microsoft.com/en-us/library/office/aa164502(v=office.10).aspx
您的代码正在做什么......
创建字典对象并分配给变量d
Set d = CreateObject("scripting.dictionary")
将指定范围常量的值指定给范围数组a
a = Range(rng)
确定范围数组中的最小值和最大值a
mx = Application.Max(a): mn = Application.Min(a)
对数组c
进行重新处理,以便在mn
和mx
ReDim c(1 To mx - mn + 1, 1 To 1)
将范围数组a
中的每个项目放入字典对象d
For i = 1 To UBound(a): d(a(i, 1)) = 1: Next i
从mn
到mx
的循环,基本上检查字典d
中是否存在此值,如果不存在,则将该值放入数组c
强>
For i = mn To mx
If d(i) <> 1 Then k = k + 1: c(k, 1) = i
Next i
将数组c
打印到工作表
Range("d2").Resize(k) = c
更新:可能修改为:
Const rng As String = "$a$2:$a$218"
Sub DoThis()
Dim d As Object, a, c()
Dim i As Long, mx As Long, mn As Long
Set d = CreateObject("scripting.dictionary")
a = Range(rng)
mx = Application.Max(a): mn = Application.Min(a)
For i = mn To mx: d(i) = True: Next i
For i = 1 To UBound(a, 1)
'# You should not actually NEED to use the If d.Exists,
' you can probably just do:
' d.Remove(a(i, 1))
' but just in case, I test to see if it exists:
If d.Exists(a(i, 1)) Then d.Remove(a(i, 1))
Next i
Range("d2").Resize(UBound(d.Keys()) + 1) = Application.Transpose(d.Keys())
End Sub