hiko-blog

VBA業務改善

MENU

配列を使用して日付を変換

Sub ConvertDateFormatWithArray()
    Dim lastRow As Long
    Dim dateValues As Variant
    Dim convertedDates() As Variant
    Dim i As Long
    Dim yyyy As String
    Dim mm As String
    Dim dd As String
    
    ' 最終行を取得
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    
    ' A列の値を配列に読み込む
    dateValues = Range("A1:A" & lastRow).Value
    
    ' 出力用の配列をリサイズ
    ReDim convertedDates(1 To lastRow, 1 To 1)
    
    ' 配列内の日付を変換
    For i = 1 To UBound(dateValues, 1)
        If Len(dateValues(i, 1)) = 8 Then ' 8桁の場合のみ変換
            yyyy = Left(dateValues(i, 1), 4)
            mm = Mid(dateValues(i, 1), 5, 2)
            dd = Right(dateValues(i, 1), 2)
            convertedDates(i, 1) = yyyy & "/" & mm & "/" & dd
        Else
            convertedDates(i, 1) = dateValues(i, 1) ' 変換不要ならそのままセット
        End If
    Next i
    
    ' 変換した日付をセルに書き戻す
    Range("b1:b" & lastRow).Value = convertedDates
End Sub

 

'//---------------------------------------------------------------

Sub ConvertDateFormat()
    Dim lastRow As Long
    Dim rng As Range
    Dim cell As Range
    Dim dateString As String
    Dim convertedDate As Date
    Dim resultArray() As Variant
    Dim i As Long
    
    ' 最終行を取得
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    ' 対象のセル範囲を指定(A列の最初のセルから最終行まで)
    Set rng = Range("A1:A" & lastRow)
    
    ' 結果を格納する配列の初期化
    ReDim resultArray(1 To lastRow, 1 To 1)
    
    ' セル範囲内の各セルに対して処理を行う
    For i = 1 To lastRow
        ' セルの値を文字列として取得
        dateString = CStr(rng.Cells(i, 1).Value)
        
        ' 文字列がyyyymmdd形式であるかどうかを確認
        If Len(dateString) = 8 And IsNumeric(dateString) Then
            ' yyyymmdd形式の日付をyyyy/mm/dd形式に変換
            convertedDate = DateSerial(Left(dateString, 4), Mid(dateString, 5, 2), Right(dateString, 2))
            ' 変換した日付を配列に格納
            resultArray(i, 1) = Format(convertedDate, "yyyy/mm/dd")
        Else
            ' エラーまたは無効な日付の場合は元の値をそのまま格納
            resultArray(i, 1) = rng.Cells(i, 1).Value
        End If
    Next i
    
    ' 変換した結果をB列に出力
    rng.Offset(0, 1).Value = resultArray
End Sub

 

'//------------------------------------------

’配列でないパターン
Sub ConvertDateFormat2()

    Dim rng As Range
    Dim cell As Range
    Dim dateValue As String
    Dim convertedDate As String
    Dim yyyy As String
    Dim mm As String
    Dim dd As String
    
    ' 変換するセル範囲を指定(A列の最終行まで)
    Set rng = Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
    
    ' セル範囲内の各セルに対して処理を行う
    For Each cell In rng
        ' セルの値を文字列として取得
        dateValue = cell.Value
        
        ' yyyymmdd形式の日付をyyyy/mm/dd形式に変換
        If Len(dateValue) = 8 Then ' 8桁の場合のみ処理を行う
            yyyy = Left(dateValue, 4)
            mm = Mid(dateValue, 5, 2)
            dd = Right(dateValue, 2)
            convertedDate = yyyy & "/" & mm & "/" & dd
            
            ' 変換した日付をセルにセット
            cell.Value = convertedDate
        End If
    Next cell
End Sub