将 Listobject Range 传递给数组并出现错误 "out of range"
Passing Listobject Range to array and getting error "out of range"
为了在循环 Listobject 的数据范围的思想值时提高我的代码速度,我想将列的值传递给数组并循环遍历数组而不是遍历 Listobject 的值。
我见识到了
从那里我详细阐述了这段代码。
'passing the list object to a variable
Dim SCtbl As ListObject
Set SCtbl = ThisWorkbook.Worksheets("sc").ListObjects(1)
'dimensioning the array (as variant)
Dim ListofSC As Variant
ListofSC = SCtbl.ListColumns("long_shortcut").DataBodyRange.Value
MsgBox (LBound(ListofSC))
MsgBox (UBound(ListofSC))
MsgBox (ListofSC(1))
第一条消息给出结果1
第二条消息给出结果 708(listobject 的行项)
但是当访问元素时,我得到元素 1 中的下标超出范围。
ListofSC实际上是一个普通的1维数组吗?
如果是这样,为什么我不能访问这些值?
谢谢。
当您将数据从 Excel 范围复制到 Variant
时,Excel returns 二维数组。当您的源范围是单列时,您可以通过将数组第二维的索引设置为 1 来访问元素,例如:
MsgBox (ListofSC(1, 1))
希望对您有所帮助
为了在循环 Listobject 的数据范围的思想值时提高我的代码速度,我想将列的值传递给数组并循环遍历数组而不是遍历 Listobject 的值。
我见识到了
'passing the list object to a variable
Dim SCtbl As ListObject
Set SCtbl = ThisWorkbook.Worksheets("sc").ListObjects(1)
'dimensioning the array (as variant)
Dim ListofSC As Variant
ListofSC = SCtbl.ListColumns("long_shortcut").DataBodyRange.Value
MsgBox (LBound(ListofSC))
MsgBox (UBound(ListofSC))
MsgBox (ListofSC(1))
第一条消息给出结果1 第二条消息给出结果 708(listobject 的行项)
但是当访问元素时,我得到元素 1 中的下标超出范围。
ListofSC实际上是一个普通的1维数组吗? 如果是这样,为什么我不能访问这些值?
谢谢。
当您将数据从 Excel 范围复制到 Variant
时,Excel returns 二维数组。当您的源范围是单列时,您可以通过将数组第二维的索引设置为 1 来访问元素,例如:
MsgBox (ListofSC(1, 1))
希望对您有所帮助