VBA CDATE | Excel VBAでCDATEを使用する方法は?(例付き)

VBAのCDATE関数

VBA CDATEは、テキストまたは文字列のいずれかのデータ型を日付データ型に変換するデータ型変換関数です。値が日付データ型に変換されたら、日付をいじることができます。

CDATEの構文

以下は、VBAのCDATE関数の構文です。

式:式は、文字列またはテキスト値、あるいは日付データ型に変換される値を含む変数です。

CDATEは、作業中のコンピューターの日付と時刻の形式を識別し、指定された値を同じ日付データ型に変換します。日と月のみを指定し、年を無視する場合、CDATE関数はシステムの年を取得し、指定された日と月とともに表示します。

以下のセクションで、ますます多くの例を見ていきます。

Excel VBAでCDATE関数を使用するにはどうすればよいですか?

ExcelvbaのCDATE関数の例。

このVBACDATE Excelテンプレートはここからダウンロードできます– VBA CDATEExcelテンプレート

例1

CDATEの例を示す前に、まず以下のコードを見てください。

コード:

 Sub CDATE_Example1()Dim k As String k = "25-12" MsgBox k End Sub 

上記の変数「k」では、値を「25-12」として割り当てました。このコードを実行すると、VBAのメッセージボックスに同じ値が表示されます。

ただし、これはVBACDATE関数を使用して日付に変換できます。このために、もう1つの変数をDateとして定義します。

コード:

 Dim k1 As Date 

この変数「k1」にCDATE関数を割り当て、文字列「25-12」を保持する変数「k」を指定します。また、メッセージボックスには、「k」ではなく「k1」の変数値を表示します。

コード:

k1 = CDate(k)

次に、コードを実行して、メッセージボックスに結果を表示します。

したがって、結果は「2019年12月25日」になります。

私たちが提供した価値をよく見てください。私たちは年に提供していない「25-12」を提供しました。

私のシステムでこの記事を書いている現在の年は2019年だったので、VBA CDATEは文字列値「25-12」を日付に変換し、システム年2019をそれに追加しました。したがって、最終結果は2019年12月25日、つまり2019年12月25日のようになります。

例2

次に、以下のコードを見てください。

コード:

 Sub CDATE_Example2()Dim k As Variant Dim kResult As Date k = 43889 kResult = CDate(k)MsgBox kResult End Sub 

上記の変数「k」のコードでは、番号「43889」を適用しました。これがシリアル番号であることは誰もが知っていますが、別の変数「KResult」については、「CDATE」関数を使用してこの値を日付に変換しました。

メッセージボックスに表示される変数「kResult」の同じ結果。

コードを実行して、関数「CDATE」の魔法を見てください。

It shows the result as “2/28/2020”, if you are not familiar with dates in excel then you must be wondering how did this happen.

For example, enter the same number (43889) in one of the cells in the spreadsheet.

For this apply the format as “DD-MM-YYYY”.

Now click on Ok and see the result.

Now the result has changed from a serial number to date. Because we have applied date format top the serial number it has shown the respective date.

So this means the serial number 43889 is equal to the date 28-02-2020.

So in our VBA code CDATE function has executed the same thing by converting the string value to a date data type.

Example #3

For this example look at the below code.

 Sub CDATE_Example3() Dim Value1 Dim Value2 Dim Value3 Value1 = "December 24, 2019" Value2 = #6/25/2018# Value3 = "18:30:48 PM" MsgBox CDate(Value1) MsgBox CDate(Value2) MsgBox CDate(Value3) End Sub 

When we run this code we will get the below results.

So, all the values are converted to the date data type with the CDATE function.

Things to Remember

  • CDATE converts only numbers and string values to the date data type.
  • This is useful when we use it with other functions.
  • If the wrong data type value is supplied then we will get type mismatch error.
  • Since date and time are part of serial number it converts time as well as proper time.