0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Excel VBA】Year関数|日付から「年」を取り出す方法と注意点

Last updated at Posted at 2025-07-09

Year関数の使い方と注意点

Year関数は、指定した日付から「年」の部分だけを取得する関数です。

構文

Year(日付)
  • 日付 : 日付を表すDate型の値、もしくは日付として解釈可能な文字列
  • 戻り値 : 日付の「年」(Integer型)

使用例

日付から年を取得する

Sub Sample()
    Dim Mydate As Date
    Mydate = #2025/01/02#
    Debug.Print Year(Mydate)
End Sub

▶ 出力結果

2025

Now関数の結果から年を取得する

Sub Sample()
    Debug.Print Year(Now)
End Sub

▶ 出力結果(実行が2025年の場合)

2025

日付の年ごとに処理を分ける

Sub Sample()
    Dim Mydate As Date
    Mydate = DateSerial(2024, 12, 31)
    
    If Year(Mydate) < 2025 Then
        Debug.Print "2024年以前です"
    Else
        Debug.Print "2025年以降です"
    End If
End Sub

▶ 出力結果

2024年以前です

⚠️注意

日付でない値を渡すとエラーになることも

引数にはDate型の値を渡すのが一般的です。
文字列で渡す場合はExcel VBAが日付として解釈できる形式である必要があります。

Sub Sample()
    On Error Resume Next

    Err.Clear
    Debug.Print Year("2025.07.09")    ' 区切り文字が不正
    If Err.Number <> 0 Then Debug.Print "2025.07.09 : エラー:" & Err.Description

    Err.Clear
    Debug.Print Year("2025年13月1日") ' 13月は存在しない
    If Err.Number <> 0 Then Debug.Print "2025年13月1日 : エラー:" & Err.Description
    
    Err.Clear
    Debug.Print Year("2025/07/32")    ' 日付が存在しない
    If Err.Number <> 0 Then Debug.Print "2025/07/32 : エラー:" & Err.Description
    
    Err.Clear
    Debug.Print Year("07-2025-09")    ' 順序・区切りが不正
    If Err.Number <> 0 Then Debug.Print "07-2025-09 : エラー:" & Err.Description
    
    Err.Clear
    Debug.Print Year("来年")          ' 自然言語は無効
    If Err.Number <> 0 Then Debug.Print "来年 : エラー:" & Err.Description
    
    On Error GoTo 0
End Sub

▶ 出力結果(実行が2025年の場合)

2025.07.09 : エラー:型が一致しません。
2025年13月1日 : エラー:型が一致しません。
2025/07/32 : エラー:型が一致しません。
07-2025-09 : エラー:型が一致しません。
来年 : エラー:型が一致しません。

上記ではエラー発生時にエラーを無視して次の処理を実行するよう記述していますが、
エラーを無視する記述が無い場合、エラー時に処理が止まってしまいます。
引数に渡す内容には注意しましょう。

関連するVBA関数

その他のVBA関数

【Excel VBA】VBAでよく使う関数一覧&基本の使い方

参考リンク

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?