VBAの変数の使い方

投稿日: 2024年5月19日

VBA(Visual Basic for Applications)での変数の使い方について説明します。

まず変数を使わないとどうなるか?
変数を使わない場合、同じ値を何度も直接コード内に記述することになります。
これにより、冗長なコードが増え、プログラム全体が長くなります。

Sub CalculateAndReportPrices()
    ' 商品の価格
    MsgBox "Price of item 1: " & (100 * 1.08)
    MsgBox "Price of item 2: " & (200 * 1.08)
    MsgBox "Price of item 3: " & (150 * 1.08)
    MsgBox "Price of item 4: " & (50 * 1.08)
    MsgBox "Price of item 5: " & (75 * 1.08)
    
    ' 商品の価格の合計
    MsgBox "Total price: " & ((100 * 1.08) + (200 * 1.08) + (150 * 1.08) + (50 * 1.08) + (75 * 1.08))
    
    ' 割引後の価格
    MsgBox "Discounted price of item 1: " & ((100 * 1.08) * 0.9)
    MsgBox "Discounted price of item 2: " & ((200 * 1.08) * 0.9)
    MsgBox "Discounted price of item 3: " & ((150 * 1.08) * 0.9)
    MsgBox "Discounted price of item 4: " & ((50 * 1.08) * 0.9)
    MsgBox "Discounted price of item 5: " & ((75 * 1.08) * 0.9)
    
    ' 割引後の価格の合計
    MsgBox "Total discounted price: " & (((100 * 1.08) * 0.9) + ((200 * 1.08) * 0.9) + ((150 * 1.08) * 0.9) + ((50 * 1.08) * 0.9) + ((75 * 1.08) * 0.9))
    
    ' 平均価格
    MsgBox "Average price: " & (((100 * 1.08) + (200 * 1.08) + (150 * 1.08) + (50 * 1.08) + (75 * 1.08)) / 5)
    
    ' 割引後の平均価格
    MsgBox "Average discounted price: " & ((((100 * 1.08) * 0.9) + ((200 * 1.08) * 0.9) + ((150 * 1.08) * 0.9) + ((50 * 1.08) * 0.9) + ((75 * 1.08) * 0.9)) / 5)
End sub

このコードは、商品1から5の価格を計算し、それぞれに税金(8%)を追加してメッセージボックスに表示します。
次に、すべての商品の合計価格を計算して表示します。
その後、各商品の割引価格(10%の割引)を計算して表示します。
割引後のすべての商品の合計価格を計算して表示します。

これを変数ありで変更するとこうなります。

Sub CalculateAndReportPrices()
    ' 商品の価格
    Dim price1 As Double
    Dim price2 As Double
    Dim price3 As Double
    Dim price4 As Double
    Dim price5 As Double
    Dim taxRate As Double
    Dim discountRate As Double
    Dim totalPrice As Double
    Dim totalDiscountedPrice As Double
    Dim averagePrice As Double
    Dim averageDiscountedPrice As Double
    
    ' 値を設定
    price1 = 100
    price2 = 200
    price3 = 150
    price4 = 50
    price5 = 75
    taxRate = 1.08
    discountRate = 0.9
    
    ' 税込み価格を計算
    Dim priceWithTax1 As Double
    Dim priceWithTax2 As Double
    Dim priceWithTax3 As Double
    Dim priceWithTax4 As Double
    Dim priceWithTax5 As Double
    
    priceWithTax1 = price1 * taxRate
    priceWithTax2 = price2 * taxRate
    priceWithTax3 = price3 * taxRate
    priceWithTax4 = price4 * taxRate
    priceWithTax5 = price5 * taxRate
    
    MsgBox "Price of item 1: " & priceWithTax1
    MsgBox "Price of item 2: " & priceWithTax2
    MsgBox "Price of item 3: " & priceWithTax3
    MsgBox "Price of item 4: " & priceWithTax4
    MsgBox "Price of item 5: " & priceWithTax5
    
    ' 税込み価格の合計を計算
    totalPrice = priceWithTax1 + priceWithTax2 + priceWithTax3 + priceWithTax4 + priceWithTax5
    MsgBox "Total price: " & totalPrice
    
    ' 割引後の価格を計算
    Dim discountedPrice1 As Double
    Dim discountedPrice2 As Double
    Dim discountedPrice3 As Double
    Dim discountedPrice4 As Double
    Dim discountedPrice5 As Double
    
    discountedPrice1 = priceWithTax1 * discountRate
    discountedPrice2 = priceWithTax2 * discountRate
    discountedPrice3 = priceWithTax3 * discountRate
    discountedPrice4 = priceWithTax4 * discountRate
    discountedPrice5 = priceWithTax5 * discountRate
    
    MsgBox "Discounted price of item 1: " & discountedPrice1
    MsgBox "Discounted price of item 2: " & discountedPrice2
    MsgBox "Discounted price of item 3: " & discountedPrice3
    MsgBox "Discounted price of item 4: " & discountedPrice4
    MsgBox "Discounted price of item 5: " & discountedPrice5
    
    ' 割引後の価格の合計を計算
    totalDiscountedPrice = discountedPrice1 + discountedPrice2 + discountedPrice3 + discountedPrice4 + discountedPrice5
    MsgBox "Total discounted price: " & totalDiscountedPrice
    
    ' 平均価格を計算
    averagePrice = totalPrice / 5
    MsgBox "Average price: " & averagePrice
    
    ' 割引後の平均価格を計算
    averageDiscountedPrice = totalDiscountedPrice / 5
    MsgBox "Average discounted price: " & averageDiscountedPrice
End Sub

ここで税金が8%から10%になった場合、変数のない場合は1.08の部分を1.1に変更する必要があります。全部変更をかけるのですから漏れ無くするのは大変です。
変数がある場合は、値の設定している「taxRate = 1.08」を「taxRate = 1.1」に変更するだけで全ての計算が変更されます。

変数を強制する方法

VBAには「Dim」で変数を宣言することができます。「Dim」とは「Dimension」(寸法)の略です。
「Dim」を省略して変数を設定することも可能ですが、変数を宣言せずに使用すると、VBAは新しい変数として認識してしまうため、予期せぬ結果を招くことがあります。

Sub Example()
    intValue = 1
    intValu = intValue + 5
    MsgBox intValue
End Sub

このコードを実行すると本来の結果は6が出る予定でしたが3行目でタイポをして本来の結果とは違う数値がでました。
このミスを防ぐ方法に「Option Explicit」を追加すると変数が強制されます。
「Option Explicit」を使用すると、すべての変数は使用する前に必ず宣言しなければなりません。これにより、タイポや誤った変数名の使用を防ぐことができます。
設定方法は「ツール」タブをクリックしその中の「オプション」をクリックします。

オプションウィンドウが表示され「編集」タブの「変数の宣言を強制する」にチェックをいれ「OK」ボタンをクリックします。

標準モジュールで新規にモジュールを作成するとコードウィンドウに「Option Explicit」のコードが組み込まれます。これで変数が強制されます。

この状態で先ほどの変数なしのコードを追加します。

Option Explicit

Sub Example()
    intValue = 1
    intValu = intValue + 5
    MsgBox intValue
End Sub

実行するとエラーになります。

エラーが発生した場合は画面に黄色で表示されますがどこがエラーになっている箇所か詳しい場所まではわかりません。注意してください。
「リセット」ボタンを押すと解除されます。

変数を宣言したコードに修正します。

Option Explicit

Sub Example()
    ' 変数を宣言
    Dim intValue As Integer
    
    intValue = 1
    intValue = intValue + 5
    MsgBox intValue
End Sub

これで実行するとコードが通ります。結果は6になります。
「Option Explicit」を使用して変数を強制的に宣言することは、エラー防止、コードの可読性向上、パフォーマンス改善、デバッグの容易化、コードの信頼性向上といった多くのメリットをもたらします。

変数Stringの使い方

文字列の代入

文字列に値を代入するには、「”」を使って文字で囲います。

Sub Example()
    Dim myString As String
    myString = "Hello, World!"
    MsgBox myString
End Sub

文字列の結合

複数の文字列を結合するには、「&」演算子を使用します。
「&」を使用するときはスペースに注意してください。

Sub Example()
    Dim firstName As String
    Dim lastName As String
    Dim fullName As String

    firstName = "太郎"
    lastName = "山田"
    fullName = lastName & " " & firstName
    MsgBox fullName
End Sub

部分文字列を取得

文字列の一部を取得するには、Mid関数を使用します。
VBAのMid関数は、文字列の一部を抽出するために使用される関数です。この関数は、指定した位置から始まり、指定した長さだけ文字列を切り取ります。Mid関数の構文は次の通りです。
「Mid(文字列, 開始位置, [長さ])」

  • 文字列: 対象の文字列。
  • 開始位置: 抽出を開始する位置(1から始まる)。
  • 長さ(省略可能): 抽出する文字数。
Sub Example()
    Dim myString As String
    Dim subString As String
    
    myString = "Hello, World!"
    subString = Mid(myString, 1, 5)  ' myStringの最初の5文字を取得
    MsgBox subString
End Sub

文字列の検索

文字列内で特定の文字列を検索するには、InStr関数を使用します。
ある文字列内で指定した文字列が最初に現れる位置を返すために使用される関数です。InStr関数の構文は次の通りです。
「InStr(対象文字列, 検索文字列」

Sub Example()
    Dim myString As String
    Dim position As Integer

    myString = "Hello, World!"
    position = InStr(myString, "World")  ' "World"の開始位置を取得
    MsgBox position
End Sub

大文字と小文字の変換

文字列を大文字または小文字に変換するには、UCaseおよびLCase関数を使用します。

Sub Example()
    Dim myString As String
    Dim upperCaseString As String
    Dim lowerCaseString As String

    myString = "Hello, World!"
    upperCaseString = UCase(myString)  ' すべて大文字に変換
    lowerCaseString = LCase(myString)  ' すべて小文字に変換
    
    MsgBox "大文字:" & upperCaseString & " " & "小文字" & lowerCaseString
End Sub

文字列は代入、結合、部分文字列の取得、検索、大文字・小文字の変換など、さまざまな操作が可能です。

変数Integerの使い方

整数は数値データを扱うためのデータ型で、宣言、代入、およびさまざまな操作が可能です。MsgBoxの部分で「vbCrLf」は改行コードになります。

Sub Example()
    Dim a As Integer
    Dim b As Integer
    Dim sum As Integer
    Dim difference As Integer
    Dim product As Integer
    Dim quotient As Integer
    Dim remainder As Integer

    a = 15
    b = 5

    sum = a + b         ' 加算: 20
    difference = a - b  ' 減算: 10
    product = a * b     ' 乗算: 75
    quotient = a / b    ' 除算: 3
    remainder = a Mod b ' 剰余: 0

    MsgBox sum & vbCrLf & difference & vbCrLf & product & vbCrLf & quotient & vbCrLf & remainder
End Sub

基本的な算術演算などの数に関係のある数値データを効果的に処理することができます。

変数Dateの使い方

日付の代入

日付型の変数に値を代入するには、次のようにします。
日付はyyyyを年、mmを月、dd日というフォーマットを持ち入ります。
日付を入れる場合は「#」で囲います。

Sub Example()
    Dim myDate As Date
    myDate = #2024-05-18#  ' yyyy-mm-dd形式で日付を代入

    MsgBox "日付:" & myDate
End Sub

日付と時刻を代入することもできます。

Sub Example()
    Dim myDate As Date
    myDate = #2024-05-18 12:30:00#  ' yyyy-mm-dd hh:mm:ss形式で日付と時刻を代入

    MsgBox "日付:" & myDate
End Sub

現在の日付と時刻の取得

現在の日付や時刻を取得するには、Date関数やNow関数を使用します。

Sub Example()
    Dim currentDate As Date
    Dim currentTime As Date

    currentDate = Date     ' 現在の日付を取得
    currentTime = Now      ' 現在の日付と時刻を取得

    MsgBox "現在の日付:" & currentDate
    MsgBox "現在の日付と時刻:" & currentTime
End Sub

日付の演算

日付型変数を使って日付の加算や減算を行うことができます。DateAdd関数を使用します。

Sub Example()
    Dim myDate As Date
    Dim futureDate As Date
    Dim pastDate As Date

    myDate = #2024-05-18#
    futureDate = DateAdd("d", 10, myDate)  ' myDateに10日を加算
    pastDate = DateAdd("m", -1, myDate)    ' myDateから1ヶ月を減算

    MsgBox futureDate
    MsgBox pastDate
End Sub

日付のフォーマット

日付型変数を文字列としてフォーマットするには、Format関数を使用します。

Sub Example()
    Dim myDate As Date
    Dim formattedDate As String

    myDate = #2024-05-18#
    formattedDate = Format(myDate, "yyyy年mm月dd日")    ' "2024年05月18日"形式

    MsgBox formattedDate
End Sub

日付で使用している”yyyy”や”mm”の内容です。

日付のフォーマットに使用されるプレースホルダー

以下は、日付をフォーマットするために使用される主要なプレースホルダーです:

  • d: 日(1桁または2桁)
  • dd: 日(2桁)
  • ddd: 曜日(省略形)
  • dddd: 曜日(完全形)
  • m: 月(1桁または2桁)
  • mm: 月(2桁)
  • mmm: 月(省略形)
  • mmmm: 月(完全形)
  • yy: 年(2桁)
  • yyyy: 年(4桁)
  • h: 時(1桁または2桁)
  • hh: 時(2桁)
  • n: 分(1桁または2桁)
  • nn: 分(2桁)
  • s: 秒(1桁または2桁)
  • ss: 秒(2桁)
  • AM/PM, am/pm, A/P, a/p: 午前/午後の表示

VBAでは、用途に応じて適切な変数の種類を選ぶことが重要です。今回は文字列、数値、日付と使い方を説明しましたが、今回はオブジェクト型は説明しませんでした。オブジェクト型は内容が多いので後のセル操作、シート操作などで説明します。

記事