見出し画像

時間帯が1つあったら所要時間を隣列にだすChatGPTと一緒につくったやつ

この説明は、ChatGPTで作成しています。

このプロシージャは、Excelのセルに書かれた時間帯(「12:00~13:00」など)を認識し、その所要時間を計算して隣のセルに表示するものです。Excelの操作を自動化して、時間の計算ができるようになります。以下に、プロシージャの仕組みをわかりやすく説明します。

1. 正規表現を使って時間帯を認識する

まず、このプロシージャでは「正規表現」という方法を使って、セル内にある時間帯(「12:00~13:00」のような形式)を探します。正規表現は、特定のパターンを効率的に見つけるための方法です。

コードの中で、`CreateObject("VBScript.RegExp")` という部分がありますが、これが正規表現を扱うための設定です。ここで、時間帯のパターンを設定し、セルの中身がそのパターンに合うかどうかを調べています。

2. 時間帯を分解して所要時間を計算する

時間帯が見つかると、その時間を開始時間と終了時間に分けます。例えば、「12:00~13:00」というデータがあった場合、「12:00」を開始時間、「13:00」を終了時間として認識します。

次に、所要時間を計算します。`endTime - startTime` の部分で終了時間から開始時間を引いて、所要時間が求められます。計算結果は時間単位で表示され、隣のセルに出力されます。

3. 24時間を考慮する仕組み

もし、終了時間が開始時間よりも早い場合、例えば「23:00~01:00」のように日付をまたぐ時間帯だった場合、所要時間がマイナスになってしまいます。この場合は、24時間を足して正しい所要時間を出すようにしています。

4. 結果を隣のセルに表示

所要時間が計算されると、その結果が元のセルの隣に表示されます。例えば、セルに「12:00~13:00」と書かれていたら、その右隣のセルに「1.00」時間と表示される、という仕組みです。

まとめ

このプロシージャを使うことで、Excelで時間帯が書かれたデータから簡単に所要時間を自動で計算し、作業を効率化できます。Excelの自動化やデータ処理を学び始めるには、実用的で楽しいプログラムの一つですね!


Excel VBA リファレンス | Microsoft Learn
この記事のYouTube動画はこちら

Sub 時間帯が1つあったら所要時間を隣列にだすChatGPTと一緒につくったやつ()
    Application.ScreenUpdating = False

    Dim reg As Object
    Set reg = CreateObject("VBScript.RegExp")   'オブジェクト作成
    Dim myRng As Range
    Dim txt As String
    Dim matches, match As Object
    Dim startTime, endTime As Date
    Dim duration As Double
    ' 正規表現パターンの設定
    With reg
        .Pattern = "\b([01]?[0-9]|2[0-3]):[0-5][0-9]~((24:[0-5][0-9])|([01]?[0-9]|2[0-3]):[0-5][0-9])\b"
        .IgnoreCase = True
        .Global = True
    End With

    On Error Resume Next
    ' セル範囲のループ処理
    For Each myRng In Selection
        txt = myRng.Value
        If reg.Test(txt) Then
            Set matches = reg.Execute(txt)
            
            ' マッチした場合
            For Each match In matches
                ' 時間帯の解析
                Dim times() As String
                times = Split(match.Value, "~")
                
                ' 開始時間と終了時間を変数に格納
                startTime = TimeValue(times(0))
                endTime = TimeValue(times(1))
                
                ' 所要時間を計算
                duration = endTime - startTime
                
                ' 所要時間が負の場合、24時間経過とみなす
                If duration < 0 Then
                    duration = duration + 1 ' 124時間を表す
                End If
                
                ' 所要時間を隣列に出力する
                myRng.Offset(0, 1).Value = Format(duration * 24, "0.00")
                
            Next match
        End If
    Next myRng

    Application.ScreenUpdating = True
End Sub

ハッシュタグ

#excel #vba #できること #正規表現 #時間計算 #自動化 #所要時間 #時間帯解析 #初心者向け #日付またぎ #開始時間 #終了時間 #プログラミング未経験 #チャットGPT #業務効率化 #ループ処理 #隣のセルに出力 #セル操作 #オブジェクト作成 #データ処理


English Explanation

The Procedure: Calculate Duration and Display It in the Adjacent Column

This explanation is created using ChatGPT.

This VBA procedure automates Excel to calculate the duration between two times (like "12:00~13:00") in a cell and displays the result in the adjacent column. Here’s a breakdown of how it works.

1. Using Regular Expressions to Find Time Ranges

The procedure uses regular expressions (RegEx) to detect time ranges written in a cell, such as "12:00~13:00." RegEx is a pattern-matching tool that helps efficiently find specific patterns, such as time formats, in text.

In the code, the line `CreateObject("VBScript.RegExp")` creates a RegEx object, which is then set to search for time ranges within the cells.

2. Extracting Time Ranges and Calculating Duration

When a time range is found, it’s split into the start time and end time. For example, "12:00~13:00" is split into the start time (12:00) and the end time (13:00).

Next, the duration is calculated using `endTime - startTime`. This operation computes the time difference and outputs the result in the adjacent cell, displaying the duration in hours.

3. Handling Time Ranges That Span 24 Hours

If the end time is earlier than the start time, such as in "23:00~01:00," it means the range spans into the next day. In this case, 24 hours are added to the calculated duration to ensure the result is correct.

4. Displaying the Result in the Adjacent Column

After calculating the duration, the result is displayed in the adjacent cell. For example, if the cell contains "12:00~13:00," the next cell will show "1.00" to indicate the duration is 1 hour.

Summary

This procedure is a helpful tool for automating time calculations in Excel, making data processing more efficient. It’s a fun and practical way to learn about VBA automation and data handling!


Excel VBA Reference | Microsoft Learn
Watch the YouTube video related to this article here


Hashtags

#excel #vba #automation #timecalculation #duration #regex #timespan #programmingbeginner #timehandling #24hour #celloperations #objectcreation #datahandling #chatgpt #adjacentcolumn #loopprocessing #regular_expression #outputtocell #vbascripting #timeparsing

この記事が気に入ったらサポートをしてみませんか?