ExcelVBAとか

VBAってあんまり好きじゃないんだけど、
簡単に書けるしMSOfficeでは使った方が便利なので軽くいじってみた。

とはいえ、プログラミングには疎いので表計算ソフトで遊ぶ程度なのだが。

Excelのワークシート上に計算機と称したフォームを表示するだけのマクロである。

Option Explicit

Private Sub ComboBox1_Change()
If ComboBox1.Value = "引き算" Then
With ComboBox1
Unload Me
UserForm2.Show
End With
End If
If ComboBox1.Value = "足し算" Then
With ComboBox1
Unload Me
UserForm3.Show
End With
End If
If ComboBox1.Value = "かけ算" Then
With ComboBox1
Unload Me
UserForm4.Show
End With
End If

End Sub

Private Sub CommandButton1_Click()

If TextBox1.Value = "0" Then
TextBox3.Value = "不正な値"
With TextBox1
.Value = ""
.SetFocus
End With

ElseIf TextBox1.Value = "" Then
TextBox3.Value = "値を入力!"
TextBox1.SetFocus
Exit Sub

ElseIf TextBox2.Value = "" Then
TextBox3.Value = "値を入力!"
TextBox2.SetFocus

Else
TextBox3.Value = Range("A3")
End If

End Sub

Private Sub CommandButton2_Click()
Unload Me
End Sub


Private Sub TextBox1_Change()

Range("A1").Value = TextBox1.Value
If TextBox1.Value = "" Then Exit Sub
TextBox1.Text = Format(TextBox1.Value, "#,##0")

End Sub


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 0
End If
End Sub

Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii < 48 Or KeyAscii > 57 Then
KeyAscii = 0
End If
End Sub
Private Sub TextBox2_Change()

Range("A2").Value = TextBox2.Value
If TextBox2.Value = "" Then Exit Sub
TextBox2.Text = Format(TextBox2.Value, "#,##0")

End Sub




Private Sub UserForm_Initialize()
UserForm1.Caption = "計算機"
With TextBox1
.Value = ""
.SetFocus
End With
With ComboBox1
ComboBox1.Value = "割り算"
.AddItem "引き算"
.AddItem "足し算"
.AddItem "かけ算"
End With
End Sub

こんなフォームをそれぞれ用意する。
Excelシート上には、あらかじめセル同士の計算式を仕込んでおいて

  • 入力がChangeする度にセルに転送
  • ボタンが押されたら計算結果のセルからデータを拾ってくる

だけである。

もちろんマクロがバグで停止しないように、考えられるユーザーのミスをIfではじくようにしておく。

あとは標準モジュールに

Option Explicit

Sub noname1()
Load UserForm1
UserForm1.Show vbModeless
End Sub

を仕込んで、ワークシート上にボタンを配するだけである。

計算機上からはコンボボックスを使用して四則演算を切り替えられるようにしてみた。
もちろん、違うコマンドボタンでいぢればもっと計算機らしくなる。

VBAって色々遊べるんだなって初めて気づいた今日この頃。
(実は、Accessで遊びたいと思って調べてたんだけど萎えたのでこうなった。)