この記事では、時刻をhh:mm.sss形式でフォーマットするマクロを作成します。

この例の生データは、列Eの特定の時間値で構成されています。

ArrowSampleData

この記事では、ユーザー定義関数(またはカスタム関数)「HHMMSSSFormat」を作成しました。この関数は、日付タイプを入力として受け取り、hh:mm.sss形式の文字列データ型で出力を返します。

ロジックの説明

60秒を3桁の数値に変換する「HHMMSSSFormat」関数では、定義された時間値の秒を60で割って定義された秒の分数を取得し、それを1000で乗算して3桁の数値を取得しました。

「HHMMSSSFormat」関数は、Excelシートで直接呼び出すか、他のプロシージャ(またはマクロ)内で関数を使用して使用できます。

次の画像は、Excelシートの「HHMMSSSFormat」関数を使用して時間をhh:mm.sss形式で導出した方法を示しています。

ArrowCustomFunction

また、「HHMMSSSFormat」関数を使用して現在の時刻をhh:mm.sss形式でメッセージボックスに表示する「GettingCurrentTimeinHHMMSSSFormat」マクロを作成しました。次の画像は、このマクロを3:54:30に実行したときの出力を示しています。

ArrowMacroOutput

コードについては以下に従ってください

Option Explicit

Function HHMMSSSFormat(DateTime As Date) As String

'function will return string value

'Declaring integer variable

Dim SecondValue As Integer

'Extracting seconds from DateTime parameter

SecondValue = Second(DateTime)

'Converting seconds value to three digit number

SecondValue = (SecondValue / 60) * 1000

'Change the formatting of time in the required format

HHMMSSSFormat = Format(Hour(DateTime), "00") & ":" & _

Format(Minute(DateTime), "00") & "." & Format(SecondValue, "000")



End Function

Sub GettingCurrentTimeinHHMMSSSFormat()

'Declaring string variable

Dim CurrentTime As String

'Calling custom function HHMMSSSFormat

CurrentTime = HHMMSSSFormat(Now)

'Displaying message box with Ok button only

MsgBox CurrentTime, vbOKOnly, "Current Time"

End Sub

このブログが気に入ったら、FacebookやFacebookで友達と共有してください。

皆様からのご意見をお待ちしております。私たちの仕事を改善し、あなたのために改善する方法をお知らせください。 [email protected]までご連絡ください