【发布时间】:2020-01-22 17:31:21
【问题描述】:
为了提高速度,我正在重写这个宏以使用数组而不是范围。
似乎使用 Array(key) 传递每个数组的字典名称可用于初始化 for each 循环,但随后将字典键作为数组引用则不能。我还尝试以与 for each 循环相同的方式将字典键重新初始化为数组。
有没有更好或更有效的方法来做到这一点?
Sub test2()
Dim arr, arr_1, arr_2, arr_3, arr_4, arr_5, arr_6, arr_7, totalrng As Variant
Dim rowcount, x, rowx As Long
With Sheets("sheet1")
rowcount = .Cells(Rows.Count, 1).End(xlUp).Row
Set arr_1 = .Range("D1:D" & rowcount)
Set arr_2 = .Range("F1:F" & rowcount)
Set arr_3 = .Range("H1:H" & rowcount)
Set arr_4 = .Range("J1:J" & rowcount)
Set arr_5 = .Range("L1:L" & rowcount)
Set arr_6 = .Range("N1:N" & rowcount)
Set arr_7 = .Range("P1:P" & rowcount)
Dim dict As Variant
Set dict = CreateObject("scripting.dictionary")
dict.Add Key:="arr_1", Item:=Nothing
dict.Add Key:="arr_2", Item:=Nothing
dict.Add Key:="arr_3", Item:=Nothing
dict.Add Key:="arr_4", Item:=Nothing
dict.Add Key:="arr_5", Item:=Nothing
dict.Add Key:="arr_6", Item:=Nothing
dict.Add Key:="arr_7", Item:=Nothing
For Each Key In dict
Debug.Print findrng
x = 2
For Each num In Array(Key)
arr = Array(Key)
.Cells(x, 22).Value = arr(1, 1)
.Cells(x, 23).Value = arr(1, 2)
x = x + 1
Next num
Next Key
End With
End Sub
【问题讨论】:
-
首先您应该删除引号,如
Key:=arr_1,但不确定您要做什么。 -
而且你不使用 set 来分配数组。
-
顺便说一句,arr_2 指的是 3 列,而不是 1 列。而且,arr_3 和 arr_4 指的是同一列。这些范围是否正确定义?应该是每隔一列吗?
-
这段代码有很多问题。我建议您阅读一些数组基础知识和使用字典。
-
您不能将数组用作字典键。