LoginSignup
1
1

More than 3 years have passed since last update.

VBAの配列とUBoundによる要素数について

Last updated at Posted at 2021-06-01

Sample Code

Sample
Dim list(3) As Long
list(0) = 1
list(1) = 2
list(2) = 3
list(3) = 4
Dim i As Integer
For i = 0 To UBound(list)
    list(i) = list(i) * list(i)
Next i

↓

list(0) : 1
list(1) : 4
list(2) : 9
list(3) : 16

他の言語と根本的に異なる(Different way of thinking)

VBAのループに「ー1」は必要ない。仕様を下記に記述する。
You don't need a "-1" in a VBA loop. The specifications are as follows.

① 配列に定義したアイテム数よりも1つ多くアイテムが生成される

下記のように記述した場合、アイテムは4個生成される。つまり、0~3のキーが生成される。
(1) One more item will be generated than the number of elements defined in the array.
If you write as follows, 4 items will be generated. So, That is, keys 0 to 3 are generated.

List
Dim list(3) As Long
↓
[list(0), list(1), list(2), list(3)]

② UBoundは定義されている数よりも1つ少ない数を取得する

先ほどの①の変数「list」のアイテム数を取得すると3となる。つまり、キーの最大値を取得する。
(UBound:UpperBoundの略)
(2) UBound is one less than the defined number.
If you get the number of items in the variable "list" in (1) above, you will get 3. That is, get the maximum value of the key.

UBound
UBound(list)
↓
3

③ 配列の定義にUBoundを使用したい場合、ReDimを使う

なお、ReDimは再定義という意味であり、アイテム数を途中で変更することも可能。
(3) If you want to use UBound to define the array, use ReDim.
ReDim is a redefinition, and it is possible to change the number of items on the way.

ReDim
Dim list(3) As Long
ReDim anotherList(UBound(list)) As Long
ReDim anotherList(10) As Long

これを書いた理由(Why i wrote this)

どこにも分かりやすく書いてないから。
Because, It is not written anywhere in an easy-to-understand manner.
どうせまた検索することになるから。
Because, I'll look for it again.

付録

Integer型は「-32,768 ~ 32,767」であり、すぐにOverFlowする。
無限ループ回避には適しているが、ビックデータを扱うならLong型を使うと良い。
Good for avoiding infinite loops, but use the Long type when dealing with big data.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1