📊 Excel VBA Top100
🔧

GetCurrentDateTime

ユーティリティ

現在の日時を取得し、セクション/セルに書き込む

🎬 デモGIF準備中

📖 使い方

  1. VBAエディタを開く(Alt + F11)
  2. モジュールを挿入(挿入 > モジュール)
  3. 下記VBAコードをコピー&ペースト
  4. ブック上で実行(Alt + F8 でマクロ選択)
💡 実行例: 実行すると現在の日時をアクティブシートのセルに書き込む

💻 VBAコード

' GetCurrentDateTime
' -----------------
' Macro Name: GetCurrentDateTime
' Description: 現在の日時を取得し、セクション/セルに書き込む
' Parameters: なし
' Returns: なし
' Usage: 実行すると現在の日時をアクティブシートのセルに書き込む
' -----------------

Sub GetCurrentDateTime()
    Dim ws As Worksheet
    Dim cellAddr As String
    Dim formatType As String
    Dim currentDT As Date

    On Error GoTo ErrorHandler

    Set ws = ActiveSheet

    cellAddr = InputBox("書き込み先のセルアドレスを入力:", "日時取得", "A1")

    If cellAddr = "" Then
        Exit Sub
    End If

    formatType = InputBox("表示形式を選択:" & vbCrLf & _
                "1: yyyy/mm/dd hh:nn:ss" & vbCrLf & _
                "2: yyyy/mm/dd" & vbCrLf & _
                "3: hh:nn:ss" & vbCrLf & _
                "4: gggee年mm月dd日", "形式選択", "1")

    currentDT = Now

    Select Case formatType
        Case "1"
            ws.Range(cellAddr).NumberFormat = "yyyy/mm/dd hh:nn:ss"
        Case "2"
            ws.Range(cellAddr).NumberFormat = "yyyy/mm/dd"
        Case "3"
            ws.Range(cellAddr).NumberFormat = "hh:nn:ss"
        Case "4"
            ws.Range(cellAddr).NumberFormat = "gggee年mm月dd日"
        Case Else
            MsgBox "無効な選択です。", vbExclamation
            Exit Sub
    End Select

    ws.Range(cellAddr).Value = currentDT

    MsgBox "現在日時を書き込みました: " & Format(currentDT, "yyyy/mm/dd hh:nn:ss"), vbInformation
    Exit Sub

ErrorHandler:
    MsgBox "エラーが発生しました: " & Err.Description, vbCritical
End Sub