是否有一种方法可以将.Range
对象完全存储在内存中?
我想将范围存储为字典值,然后能够将范围解包到其他位置。但是在拆包之前,原始范围会被修改。
这是我将范围存储在字典中的代码:
Sub range_to_dict()
Application.EnableEvents = False
Dim d As New scripting.Dictionary
Dim rng As Range
Dim rw As Range
Dim paste_loc As Range
Set rng = Range("A1:B13")
Set paste_loc = rng.Offset(rng.Rows.Count + 2, 0).Resize(1, 1)
For Each rw In rng.Rows
d.Add (rw.Cells(1).Value), rw
Next rw
For Each k In d.Keys
d(k).Copy
paste_loc.PasteSpecial xlPasteValues
Set paste_loc = paste_loc.Offset(1, 0)
Next k
Application.EnableEvents = True
End Sub
仅当我不修改创建字典和解包之间的范围时,它才会起作用,因为在解包时,VBA仍会从工作表而不是从内存(词典)读取范围:
Sub range_to_dict()
Application.EnableEvents = False
Dim d As New scripting.Dictionary
Dim rng As Range
Dim rw As Range
Dim paste_loc As Range
Set rng = Range("A1:B13")
Set paste_loc = rng.Offset(rng.Rows.Count + 2, 0).Resize(1, 1)
For Each rw In rng.Rows
d.Add (rw.Cells(1).Value), rw
Next rw
'modify (clear)
For Each rw In rng.Rows
rw.Clear
Next rw
'now this will paste only empty fields
For Each k In d.Keys
d(k).Copy
paste_loc.PasteSpecial xlPasteValues
Set paste_loc = paste_loc.Offset(1, 0)
Next k
Application.EnableEvents = True
End Sub
我可以通过将每个范围单元格值存储在数组或集合中,然后将它们解压缩来实现我想要的,但是有没有那么麻烦的方法?
答案 0 :(得分:1)
不可能将Range
存储在变量(内存)中。始终只是对存储在变量中的原始范围的引用。
但是您可以将范围的值读入数组:
Dim MyArr As Variant
MyArr = Range("A1:A10").Value
如果您现在修改范围A1:A10,则该数组仍将包含旧值。
当然,您可以将它们写回到单元格中
Range("A1:A10").Value = MyArr
请注意,回写时,范围必须与数组大小相同。否则,某些值将丢失。