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】CStr関数|数値や日付を文字列(String)型に変換する方法と注意点

Last updated at Posted at 2025-07-14

CStr関数の使い方と注意点

CStr関数は、指定した値を文字列(String型)に変換する関数です。
数値・日付・論理値など、さまざまなデータ型を文字列として扱いたいときに使用します。

構文

CStr()
  • : 文字列に変換したい任意の値(数値、日付、ブール値など)
  • 戻り値 : 指定された式を文字列に変換した結果(String型)

使用例

数値を文字列に変換

Sub Sample()
    Dim Myint As Integer
    Myint = 123
    Debug.Print TypeName(Myint)
    Debug.Print TypeName(CStr(Myint))
End Sub

▶ 出力結果

Integer
String

日付を文字列に変換

Sub Sample()
    Dim Mydatetime As Date
    Mydatetime = #2025/7/14 15:30:00#
    Debug.Print CStr(Mydatetime)
End Sub

▶ 出力結果

Date
String

論理値(Boolean)を文字列に変換

Sub Sample()
    Debug.Print TypeName(True)
    Debug.Print TypeName(CStr(True))
End Sub

▶ 出力結果

Boolean
String

通貨型(Currency)を文字列に変換

Sub Sample()
    Dim price As Currency
    price = 1980.5
    
    Debug.Print TypeName(price)
    Debug.Print TypeName(CStr(price))
End Sub

▶ 出力結果

Currency
String

⚠️注意

日付・時刻の出力形式は「システムの設定」に依存する

Sub Sample()
    Debug.Print CStr(#2025/12/31 13:45:00#)
End Sub

▶ 出力結果(Windowsの地域設定が「日本」の場合)

2025/12/31 13:45:00

表示形式を明示的に指定したい場合はFormat関数を使いましょう。

Sub Sample()
   Debug.Print Format(#12/31/2025 1:45:00 PM#, "yyyy年mm月dd日 hh時nn分ss秒")
End Sub

▶ 出力結果

20251231 134500

EmptyやNullを渡すと空文字やエラーになる

Sub Sample()
   On Error Resume Next

   Debug.Print "Empty → [" & CStr(Empty) & "]"
   
   Debug.Print "Null → [" & CStr(Null) & "]"
   If Err.Number <> 0 Then Debug.Print "Null変換時のエラー:" & Err.Description
   
   On Error GoTo 0
End Sub

▶ 出力結果

Empty  []
Null変換時のエラー:Null の使い方が不正です。

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

オブジェクト型は変換できない(エラー)

Sub Sample()
   Dim obj As Object
   Set obj = CreateObject("Scripting.Dictionary")

   On Error Resume Next
   Debug.Print CStr(obj)
   If Err.Number <> 0 Then Debug.Print "オブジェクトは変換できません:" & Err.Description
   On Error GoTo 0
End Sub

▶ 出力結果

オブジェクトは変換できません:引数の数が一致していません。または不正なプロパティを指定しています。

関連する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?