LBound and Ubound conflicts in case of array which has been assigned by the Range

和自甴很熟 提交于 2019-12-01 13:35:31

By default, the subscripts/indices of VBA arrays start at 0 (this is called the lower bound of the array) and run up to the number you specify in the Dim statement (this is called the upper bound of the array). If you would prefer your array index numbers to start at 1, include the following statement at the top of the module.

Option Base 1

However when an array is populated by Range object using the Transpose method, the array Lower bound set to 1 even you are on default Zero baed mode. So array becomes 1 based.

e.g. the following data is added using Transpose method.

Array(1) = "Hola"
Array(2) = "Bonjour"
Array(3) = "Hello"
Array(4) = "Wei"

Good thing is that this array UBound tells you number of elements (4) which = UBound. Unlike if it was zero based, then number of elements = Ubound + 1.

UBound(Array) --> 4
LBound(Array) --> 1

In current 1-based scenario, the Ubound refers to the total number of elements. So in such cases you need to amend your code to track data within the array's LBound, UBound properties to avoid data loss.

And by the way, by adding Option Base 0 doesn't stop array being dimentioned to 1 based by Transpose method. Which invalids my first comment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!