[VBA] How to Branch Processing Using Option Buttons in a UserForm

目次

Introduction

In this article, we will look at how to branch processing using option buttons placed on a UserForm.

Environment:

  • OS: Windows 10 Pro
  • Version: 20H2

Background

I wanted to place two option buttons on a UserForm, “Yes” and “No,” and execute different processes depending on which one was selected.

Implementation: Branching with “Select Case True”

To achieve this, I used the Select Case True syntax. This allows for clear and explicit branching based on conditions.

Actual Code Example

Select Case True
    Case OptionButton1.Value
        Range("A1") = "Yes"
    Case OptionButton2.Value
        Range("B1") = "No"
End Select

Explanation of the Code

Select Case True

This checks for cases where the condition is True. Using this syntax makes it possible to branch explicitly based on multiple conditions.

Case OptionButton1.Value

This code is executed if “Yes” (OptionButton1) is selected (i.e., OptionButton1.Value = True).

  • Range("A1") = "Yes": Displays “Yes” in cell A1.

Case OptionButton2.Value

This code is executed if “No” (OptionButton2) is selected.

  • Range("B1") = "No": Displays “No” in cell B1.

Application Tips

In this example, we input strings (“Yes”, “No”) into cells, but you can apply this logic to various other scenarios:

  • Assigning specific formulas to cells.
  • Calling other processing routines or macros.
  • Toggling the visibility (Show/Hide) of other form elements.
  • Branching operations such as opening or saving files.

Summary

  • Option buttons on UserForms are very convenient for branching logic.
  • By using the Select Case True syntax, you can write concise branching code based on multiple options.
  • This can be applied not just to cell output, but to any kind of processing.

Through this exercise, I realized that interactive operations using UserForms can be implemented quite flexibly. Moving forward, I plan to design more complex forms that combine multiple options and input fields.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次