【发布时间】:2020-12-13 05:16:56
【问题描述】:
我的代码中有这个功能:
Function get_header(ByVal rw As Range) As Scripting.Dictionary
Dim header As New Scripting.Dictionary
Dim used As Range
Set used = Range(rw.Cells(1, 1), rw.Cells(1, rw.Cells(1, rw.Columns.Count).End(xlToLeft).Column))
For Each cl In used.Cells
header.Add cl.Value, cl.Column
Next
Set get_header = header
End Function
该函数的作用是获取表头并创建列名和相应索引的字典,因此列的顺序对于其余代码而言并不重要。
我的问题是:是否有必要使用单独的变量来存储整个循环中的值,或者我可以
- 始终编辑返回值(“get_header”),而不是只在最后传递值或
- 像这样使用 With 结构:
Function get_header(ByVal rw As Range) As Scripting.Dictionary
Dim used As Range
With rw
Set used = Range(.Cells(1, 1), .Cells(1, .Cells(1, .Columns.Count).End(xlToLeft).Column))
End With
With get_header
For Each cl In used.Cells
.Add cl.Value, cl.Column
Next
End With
End Function
另外,为什么我应该使用这些结构中的任何一个而不是其他结构? 谢谢大家的建议。
【问题讨论】:
-
尽管这最终是基于意见的,但我投票支持选项#1。 #2 为我隐藏了返回值,而 #1 是明确的。
-
除了基于意见之外,您的问题在某种意义上是令人困惑的的功能,因此并不能真正说明您似乎试图做出的对比。
-
仅供参考,如果带有
rw的工作表未激活,则常规代码模块中的这一行Set used = Range(rw.Cells(1, 1), ...将出错。像Set used = rw.Parent.Range(rw.Cells(1, 1), ...这样的东西会更健壮。