0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAのVariant型の基本

Posted at

Variant型とは

VBAのVariant型は、データ型を宣言しない変数に使用するデータ型です。
Variant型の変数には、全てのデータ型を入れることができます。

Variant型の変数には異なる型のデータを代入できる

以下の例のように、最初に変数aには数値型を代入し、次に文字列型を代入しています。このように、Variant型の変数は最初に入れたデータ型に関わらず、どのようなデータ型でも代入できます。

Option Explicit

Sub Sample()

Dim a As Variant
a = 1

'VarTypeは指定した変数のデータ型を返す関数
MsgBox VarType(a)   '2を表示。2はInteger(整数型)を表す

a = "AAA"
MsgBox VarType(a)   '8を表示。8はString(文字列型)を表す

End Sub

Variant型の変数には配列を代入できる

Variant型以外の場合、配列は「変数名()」で宣言し、値を代入します。

Option Explicit

Sub Sample()

Dim list(3) As String
list(0) = "東京"
list(1) = "大阪"
list(2) = "福岡"
Range("A1").Value = list(0)
Range("A2").Value = list(1)
Range("A3").Value = list(2)

End Sub
'A1セル:東京
'B1セル:大阪
'C1セル:福岡

Variant型の場合、配列を「変数名()」で宣言する方法と、「変数名()」を使わずに宣言する方法があります。後者の場合、後続処理でArray関数を使用します。

Option Explicit

Sub Sample()

Dim list As Variant
list = Array("東京", "大阪", "福岡")
Range("A1").Value = list(0)
Range("A2").Value = list(1)
Range("A3").Value = list(2)

End Sub

'A1セル:東京
'B1セル:大阪
'C1セル:福岡

Variant型の変数は連想配列を代入できる

連想配列とは、列と行を持っている配列のことです。
Variatn型の変数を使えば、ひとつの変数に複数範囲のセルの値をまるごと代入できます。

Option Explicit

Sub Sample()
Dim list As Variant
list = Range("A1:C3")
Range("A10:C12").Value = list

End Sub

もともとは以下の状態です。
image.png

VBAを実行すると、Variant型の変数listに入れた値が、A10~C12に代入されます。
image.png

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?