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?

VBAで構造体を戻り値とする

Posted at

背景

VBAコードの保守を行う機会があり、
関数の戻り値として複数の要素をひとまとめにして返したい場面がありました。

TypeScriptであれば、オブジェクトリテラルを用いて手軽に行うことができますが
VBAでは機能としてないため同様の方法が使えません。

類似のことがVBAでも行えないかと調べたところ、
構造体という便利な方法があったので紹介の記事となります。

やりたいこと

下記はTypeScriptで記載したサンプルコードですが、
関数の戻り値をオブジェクトリテラルにして、ひとまとめとして返しています。
このように記載した場合、呼び出し元で戻り値が扱いやすいので便利です。
VBAにおいても、これと同じようなことをしたいと考えました。

interface ReturnValue {
    result: boolean;
    message: string;
}

const sampleFunc = (): ReturnValue => {
    return {
        result : true,
        message : "成功"
    }
}

構造体を利用した戻り値作成

VBAにはオブジェクトリテラル構文の利用は機能としてないため
代替として「構造体」を用いることで解決します。
変数に定義する必要はありますが、TypeScriptの場合とほぼ同じような感触で利用が可能です。

' 先頭にPublicをつけると他モジュールから利用可能
Type ReturnValue
    result As Boolean
    message As String
End Type

Public Function SampleFunc() As ReturnValue 
    Dim returnValue As ReturnValue
    returnValue.result = True
    returnValue.message = "成功"
    SampleFunc = returnValue
End Function

あとがき

個人的に便利だと思ったのですが、
VBAコードで利用されているのを見たことがなく、勿体無いなと思っての紹介でした。

参考

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?