1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAたまによく使うもの覚え書き

Last updated at Posted at 2020-10-10

変数宣言

変数宣言を必須にする

Option Explicit

変数宣言における型指定

Dim i As Integer

Asによる型指定は全ての変数に対して必要。書かない場合はVariantになる。
私見だがVBA実行時の型エラーはだいたいこれ。

定数宣言

Const days As Integer = 366

日付

本日

Dim today As Date
today = Date

指定する

Dim a As Date
a = CDate("2020/4/1")

一ヶ月後

Dim today As Date
Dim future As Date
today = Date

future = DateAdd("m", 1, Date)

参考:DateAdd http://officetanaka.net/excel/vba/function/DateAdd.htm

ワークシートとのデータやり取り関連

単一セルから読み取り

Dim average_today As Double
average_today = Cells(row, column).Value

シート名も指定するなら次のようにする

Dim average_today As Double
average_today = Sheets("any sheet's name").Cells(row, column).Value

単一セルへ値を設定

Dim average_today As Double
average_today = 20.0
Cells(row, column).Value = average_today

複数セル or 範囲を消去

Range(Cells(startRow, startColumn), Cells(endRow, endColumn)).ClearContents

シート名も指定するなら、ちょっと煩雑だがこんな感じ

Range(Sheets("any sheet's name").Cells(startRow, startColumn), Sheets("any sheet's name").Cells(endRow, endColumn)).ClearContents

If文

If today <= tomorrow And tomorrow < next_tomorrow Then
    'do something
ElseIf today <= yesterday Or yesterday < tomorrow Then
    'do something
Else
    'do something
End If

サブルーチン内なら必要に応じてExit Subで処理を抜ける

For Loop

Sub test_loop()
    Dim i As Integer
    
    For i = 1 To 5
        MsgBox (i)
        
        If i = 4 Then
            Exit For
        End If
    
    Next i
    
    MsgBox ("end of loop")
End Sub

continueを使いたい場合はGoTo文でNext直前にラベルを貼ると良い。

Functionの戻り値

Function GetYear(today As Date)
    GetYear = Year(today)
End Function

returnは無い。Function名と同じ変数を返す。

配列インデックスの上限・下限

UBound(array)
LBound(array)

VBAコード上はindexが0オリジンだが、ワークシートからの一括読み込みだと1オリジンになる。

VBAコード上でもindexを1オリジンにする

Option Base 1

String値を返すEnumもどきを作成する

Enum Place
    Yamagata
    Sakata
    Shinjo
    Yonezawa
End Enum

Dim placeHash As Object

Sub Initialize()
    Set placeHash = CreateObject("Scripting.Dictionary")
    placeHash.Add Place.Yamagata, "山形"
    placeHash.Add Place.Sakata, "酒田"
    placeHash.Add Place.Shinjo, "新庄"
    placeHash.Add Place.Yonezawa, "米沢"
End Sub

Enumは値が数値になる(一個目が0で順次インクリメント)ので、Stringの値が欲しければDictionary型を使うと良いようだ。

参考

CDate https://www.tipsfound.com/vba/05cdate
Const http://officetanaka.net/excel/vba/statement/Const.htm
Enum https://www.tipsfound.com/vba/02017
Range https://excel-ubara.com/excelvba1/EXCELVBA311.html

1
2
1

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?