Switch関数というものがある
Switch関数というものがある
知ってました?
私は全然知らなかった。
何気なく『Programming Excel with VBA and .NET』という本を読んでいたら、59ページに、
Sub GetResponse() ' Declare variable as an enumerated value' Dim res As VbMsgBoxResult ' Get the response.' res = MsgBox("What's your response?", vbYesNoCancel) ' Test the response against possible values.' Debug.Print "Response is:", Switch(res = vbYes, "Yes", _ res = vbNo, "No", res = vbCancel, "Cancel") End Sub
In the preceding code, the variable
res
can contain any of the possible message box results.TheSwitch
function compares the variable to each of the possible responses to display an appropriate string in the Immediate window.
と書いてあった。
マ、マジっすか……?!
全然知らなかったよ!
実験
標準モジュールに次のコードを書いて実験。
リスト1 標準モジュール
Private Sub getResponse() Dim userRes As VbMsgBoxResult userRes = MsgBox("どれか選べやwww", vbYesNoCancel) Debug.Print Switch(userRes = vbYes, "ち~んw", _ userRes = vbNo, "( ´,_ゝ`)プッ", _ userRes = vbCancel, "(゚∀゚)アヒャ") End Sub
こいつを何度も実行し、その都度返答を変えてみる。
いざ、実行!
ほ、ほんまや……。
おわりに
何か、使いどころはあるかなあ。
小ネタでした。