0
0

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 1 year has passed since last update.

VBAにおけるクラスモジュールのパブリックメンバーに配列を利用する

Posted at

VBAはExcelにての利用時、Rangeなど配列を利用したいケースが多い
しかしインスタンス変数に配列を利用しようとするとエラーが発生した。

その時の一時的対処のメモ

エラー内容

VBAにおいて以下のようなクラスモジュールを作成しようとする

SampleClass
Option Explicit

Public numbers() As Long

以下のようなエラーになる
コンパイルエラー2022-10-31 164756.png

対応策

Variant型で変数宣言する
その後、Array型の値を代入すると配列として利用できる

SampleClass
Option Explicit
Public numbers As Variant

Private Sub Class_Initialize()
    numbers = Array()
End Sub

実行例

SampleModule
Public Sub Test()
    
    Dim number As Variant
    Dim cls As SampleClass
    
    Set cls = New SampleClass
    cls.numbers = Array(1,2,3)

    For Each number In cls.numbers
        Debug.Print number
    Next
    

End Sub
出力結果
 1 
 2 
 3 
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?