Str関数とCstr関数


この2つは、目的は同じ、文字列型に変換することでも返す値は違うので注意が必要。StrとCstrの比較は以下の通り。

 関数     動 作         変 換 後 の 文 字 列
----------------------------------------------------------------------
 Str  数値を文字列に変換     頭に符号を確保するための空白が入る。
 Cstr  数値を文字列に変換   そのままで変換する。 


文字列型に変換するので、安易にStr関数を使ってしまったのだが・・・。


以下のプログラムは、年月日の書いてあるセルから月の数値だけを抜き出し、1〜9月の場合は、先頭に「0」を付け、それ以外の場合は、数値をそのまま使用する。

'------------------------------------------
' 月加工プログラム(Cstr版) 
'------------------------------------------
'
    ' 日付を取得
    arrival_date = cells(8,1)

    ' 月を取得
    target_month = Month(arrival_date)
    
    ' 文字列型に変換 
    str_month = CStr(target_month)
    
    ' 0判定
    If str_month = "10" Or str_month = "11" Or str_month = "12" Then
        ' 10 , 11 , 12月の場合
        str_month = str_month
    Else
        ' 1 〜 9月の場合
        str_month = "0" & str_month
    End If


上記のプログラムで11月を処理した場合、以下の数値になり、正常に機能する。

str_month = 11


以下のプログラムは、Cstr関数をStr関数に書き直したものです。

'------------------------------------------
' 月加工プログラム(Str版) 
'------------------------------------------
'
    ' 日付を取得
    arrival_date = cells(8,1)

    ' 月を取得
    target_month = Month(arrival_date)
    
    ' 文字列型に変換 
    str_month = Str(target_month)
    
    ' 0判定
    If str_month = "10" Or str_month = "11" Or str_month = "12" Then
        ' 10 , 11 , 12月の場合
        str_month = str_month
    Else
        ' 1 〜 9月の場合
        str_month = "0" & str_month
    End If


上記のプログラムで11月を処理した場合、以下の数値になり、正常に機能しない。

 str_month = 0 11


実際には、下記の通りに処理していたんだけど・・・。

'------------------------------------------
' 月加工プログラム(Str版) 
'------------------------------------------
'
    ' 日付を取得
    arrival_date = cells(8,1)

    ' 月を取得
    target_month = Month(arrival_date)
    
    ' 文字列型に変換 
    str_month = Str(target_month)

    ' 先頭の一桁を取得
    check_month = Left(str_month, 1)
    
    ' 先頭の一桁が空白かどうかチェック
    If check_month = " " Then
        ' 末尾の1桁を取得
        temp_month = Right(str_month, 1)
        str_month = "0" & temp_month
    Else
        str_month = str_month
    End If


上記のプログラムで11月を処理した場合、以下の数値になり、正常に機能しない。

 str_month = 01


つまり、このプログラムの問題点は、実際には、10、11、12月の場合、Strを使うと、それぞれ「 10」、「 11」、「 12」となり、符号用の空白が付き、3桁になってしまうのに対して、2桁で処理をしてしまったからおかしくなってしまったのだ。


とりあえず、今後は注意しようと思う。