Dim myCollection:作为集合与作为变体
Dim myCollection: As Collection vs As Variant
下面的第一个子例程不起作用,但第二个子例程起作用。为什么?
两者之间的唯一区别是 rs 变量的类型(集合与变体)。
第一个子例程给我以下错误:
"Run-time '13': Type mismatch"
Sub It_Doesnt_Work()
Dim rg As Excel.Range, rs As Collection
Set rg = Application.Range("myRange")
Set rs = rg.CurrentRegion.Rows
Debug.Print rs.Count
End Sub
Sub It_Works()
Dim rg As Excel.Range, rs As Variant
Set rg = Application.Range("myRange")
Set rs = rg.CurrentRegion.Rows
Debug.Print rs.Count
End Sub
此 rg.CurrentRegion.Rows
的类型为 Range
,您尝试将其推入 rs As Collection
中,这是一个集合。由于 Excel 没有范围到集合的隐式转换,因此您不能这样做。
要么您编写一个显式转换这些类型的函数,要么您需要像您一样定义变量 rs As Range
或 Variant
,但 Range
会更好。
下面的第一个子例程不起作用,但第二个子例程起作用。为什么?
两者之间的唯一区别是 rs 变量的类型(集合与变体)。
第一个子例程给我以下错误:
"Run-time '13': Type mismatch"
Sub It_Doesnt_Work()
Dim rg As Excel.Range, rs As Collection
Set rg = Application.Range("myRange")
Set rs = rg.CurrentRegion.Rows
Debug.Print rs.Count
End Sub
Sub It_Works()
Dim rg As Excel.Range, rs As Variant
Set rg = Application.Range("myRange")
Set rs = rg.CurrentRegion.Rows
Debug.Print rs.Count
End Sub
此 rg.CurrentRegion.Rows
的类型为 Range
,您尝试将其推入 rs As Collection
中,这是一个集合。由于 Excel 没有范围到集合的隐式转换,因此您不能这样做。
要么您编写一个显式转换这些类型的函数,要么您需要像您一样定义变量 rs As Range
或 Variant
,但 Range
会更好。