■■■■■■■第4章 17■■■■■■■

■■■■p181プロンプト例

あなたは優秀なExcel VBAのプログラマーです。 
次の操作をするExcel VBAのプログラムを書いてください。

・フォルダー選択のダイアログボックスを開いてフォルダーを指定
・フォルダー内にあるすべてのCSVファイルを、Excelファイルに変換する
・変換したExcelファイルに、以下の書式を設定する
　　1行目の見出し行を水色に塗りつぶす
　　各列の幅を自動調整
・変換したExcelファイルは、同じフォルダーに「変換後」というサブフォルダーを作成し、その中に保存する
・マクロ名は「CSVをExcel形式に変換」とする
・このマクロは「個人用マクロブック」に保存して使う


■■■■p182コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim savePath As String
    Dim destFolder As String
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダー選択ダイアログを表示
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' 保存先「変換後」フォルダー作成
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then
        MkDir destFolder
    End If
    
    ' CSVファイルを順に処理
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        ' CSVファイルを開く
        Set wbCSV = Workbooks.Open(folderPath & "\" & fileName)
        
        ' 見出し行を水色に塗りつぶす
        With wbCSV.Sheets(1).Rows(1).Interior
            .Color = RGB(173, 216, 230) ' 水色
        End With
        
        ' 列幅を自動調整
        wbCSV.Sheets(1).Columns.AutoFit
        
        ' 保存先パスを設定
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        
        ' Excel形式で保存
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        
        ' CSVブックを閉じる
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    MsgBox "すべてのCSVファイルをExcel形式に変換しました。", vbInformation
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


■■■■p183プロンプト例

最後にExcel画面だけが残りました。Excelを終了するようにしてください。また、「変換後」フォルダーを開くようにしてください。


■■■■p184コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim savePath As String
    Dim destFolder As String
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダー選択ダイアログを表示
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' 保存先「変換後」フォルダー作成
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then
        MkDir destFolder
    End If
    
    ' CSVファイルを順に処理
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        ' CSVファイルを開く
        Set wbCSV = Workbooks.Open(folderPath & "\" & fileName)
        
        ' 見出し行を水色に塗りつぶす
        With wbCSV.Sheets(1).Rows(1).Interior
            .Color = RGB(173, 216, 230) ' 水色
        End With
        
        ' 列幅を自動調整
        wbCSV.Sheets(1).Columns.AutoFit
        
        ' 保存先パスを設定
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        
        ' Excel形式で保存
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        
        ' CSVブックを閉じる
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' 「変換後」フォルダーを開く
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' Excelを終了
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


■■■■p185プロンプト例

「0001」というID番号の「000」が消えてしましました。


■■■■p185コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim ws As Worksheet
    Dim savePath As String
    Dim destFolder As String
    Dim qt As QueryTable
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダー選択ダイアログを表示
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' 保存先「変換後」フォルダー作成
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then
        MkDir destFolder
    End If
    
    ' CSVファイルを順に処理
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        ' 新しいブックを作成
        Set wbCSV = Workbooks.Add
        Set ws = wbCSV.Sheets(1)
        
        ' CSVデータを文字列として読み込む
        Set qt = ws.QueryTables.Add(Connection:="TEXT;" & folderPath & "\" & fileName, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            .TextFilePlatform = 65001 ' UTF-8
            .TextFileColumnDataTypes = Array(1) ' 全列を文字列として読み込み
            .Refresh BackgroundQuery:=False
            .Delete
        End With
        
        ' 見出し行を水色に塗りつぶす
        With ws.Rows(1).Interior
            .Color = RGB(173, 216, 230) ' 水色
        End With
        
        ' 列幅を自動調整
        ws.Columns.AutoFit
        
        ' 保存先パスを設定
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        
        ' Excel形式で保存
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' 「変換後」フォルダーを開く
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' Excelを終了
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


■■■■p185プロンプト例

やっぱり「0」が消えてしまいます。


■■■■p186コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim ws As Worksheet
    Dim savePath As String
    Dim destFolder As String
    Dim qt As QueryTable
    Dim colCount As Long
    Dim colTypes() As Long
    Dim tempText As String
    Dim fNum As Integer
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダー選択ダイアログを表示
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' 保存先「変換後」フォルダー作成
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then
        MkDir destFolder
    End If
    
    ' CSVファイルを順に処理
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        ' 1行目の列数を取得
        fNum = FreeFile
        Open folderPath & "\" & fileName For Input As #fNum
        Line Input #fNum, tempText
        Close #fNum
        colCount = UBound(Split(tempText, ",")) + 1
        
        ' 列数分の文字列型配列を作成（2=文字列）
        ReDim colTypes(1 To colCount)
        Dim i As Long
        For i = 1 To colCount
            colTypes(i) = 2
        Next i
        
        ' 新しいブックを作成
        Set wbCSV = Workbooks.Add
        Set ws = wbCSV.Sheets(1)
        
        ' CSVデータを文字列として読み込む
        Set qt = ws.QueryTables.Add(Connection:="TEXT;" & folderPath & "\" & fileName, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            .TextFilePlatform = 65001 ' UTF-8
            .TextFileColumnDataTypes = colTypes
            .Refresh BackgroundQuery:=False
            .Delete
        End With
        
        ' 見出し行を水色に塗りつぶす
        With ws.Rows(1).Interior
            .Color = RGB(173, 216, 230)
        End With
        
        ' 列幅を自動調整
        ws.Columns.AutoFit
        
        ' 保存先パスを設定
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        
        ' Excel形式で保存
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' 「変換後」フォルダーを開く
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' Excelを終了
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


■■■■p187プロンプト例

「0001」のゼロは消えなくなりましたが、ファイルによっては文字化けします。


■■■■p187コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim ws As Worksheet
    Dim savePath As String
    Dim destFolder As String
    Dim qt As QueryTable
    Dim colCount As Long
    Dim colTypes() As Long
    Dim tempText As String
    Dim fNum As Integer
    Dim bom(1 To 3) As Byte
    Dim isUTF8 As Boolean
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' フォルダー選択ダイアログを表示
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' 保存先「変換後」フォルダー作成
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then
        MkDir destFolder
    End If
    
    ' CSVファイルを順に処理
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        ' ---- 文字コード判定（BOMチェック）----
        isUTF8 = False
        fNum = FreeFile
        Open folderPath & "\" & fileName For Binary As #fNum
        Get #fNum, , bom
        Close #fNum
        If bom(1) = &HEF And bom(2) = &HBB And bom(3) = &HBF Then
            isUTF8 = True
        End If
        
        ' ---- 列数取得 ----
        fNum = FreeFile
        Open folderPath & "\" & fileName For Input As #fNum
        Line Input #fNum, tempText
        Close #fNum
        colCount = UBound(Split(tempText, ",")) + 1
        
        ' 列数分の文字列型配列を作成（2=文字列）
        ReDim colTypes(1 To colCount)
        Dim i As Long
        For i = 1 To colCount
            colTypes(i) = 2
        Next i
        
        ' ---- 新しいブックを作成 ----
        Set wbCSV = Workbooks.Add
        Set ws = wbCSV.Sheets(1)
        
        ' ---- CSVを読み込み（文字コードを切り替え）----
        Set qt = ws.QueryTables.Add(Connection:="TEXT;" & folderPath & "\" & fileName, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            If isUTF8 Then
                .TextFilePlatform = 65001 ' UTF-8
            Else
                .TextFilePlatform = 932   ' Shift_JIS
            End If
            .TextFileColumnDataTypes = colTypes
            .Refresh BackgroundQuery:=False
            .Delete
        End With
        
        ' 見出し行を水色に塗りつぶす
        With ws.Rows(1).Interior
            .Color = RGB(173, 216, 230)
        End With
        
        ' 列幅を自動調整
        ws.Columns.AutoFit
        
        ' 保存先パスを設定
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        
        ' Excel形式で保存
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' 「変換後」フォルダーを開く
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' Excelを終了
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


■■■■p189プロンプト例

「BOM判定付きShift_JIS/UTF-8自動切替版」にしてください。


■■■■p189コード例

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim ws As Worksheet
    Dim savePath As String
    Dim destFolder As String
    Dim qt As QueryTable
    Dim colCount As Long
    Dim colTypes() As Long
    Dim tempText As String
    Dim fNum As Integer
    Dim bom(1 To 3) As Byte
    Dim isUTF8 As Boolean
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' --- フォルダー選択 ---
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        Exit Sub
    End If
    
    ' --- 保存先「変換後」フォルダー作成 ---
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then MkDir destFolder
    
    ' --- CSVファイル取得 ---
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        
        ' --- UTF-8 / Shift_JIS 判定 ---
        isUTF8 = False
        
        ' 1. BOMチェック
        fNum = FreeFile
        Open folderPath & "\" & fileName For Binary As #fNum
        Get #fNum, , bom
        Close #fNum
        If bom(1) = &HEF And bom(2) = &HBB And bom(3) = &HBF Then
            isUTF8 = True
        Else
            ' 2. BOMなしの場合は簡易UTF-8判定
            If IsUTF8File(folderPath & "\" & fileName) Then
                isUTF8 = True
            End If
        End If
        
        ' --- 列数取得（ゼロ落ち防止用）---
        fNum = FreeFile
        Open folderPath & "\" & fileName For Input As #fNum
        Line Input #fNum, tempText
        Close #fNum
        colCount = UBound(Split(tempText, ",")) + 1
        
        ReDim colTypes(1 To colCount)
        Dim i As Long
        For i = 1 To colCount
            colTypes(i) = 2 ' 全列文字列
        Next i
        
        ' --- 新しいブック ---
        Set wbCSV = Workbooks.Add
        Set ws = wbCSV.Sheets(1)
        
        ' --- CSV読み込み ---
        Set qt = ws.QueryTables.Add(Connection:="TEXT;" & folderPath & "\" & fileName, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            If isUTF8 Then
                .TextFilePlatform = 65001 ' UTF-8
            Else
                .TextFilePlatform = 932   ' Shift_JIS
            End If
            .TextFileColumnDataTypes = colTypes
            .Refresh BackgroundQuery:=False
            .Delete
        End With
        
        ' --- 見出し行を水色に ---
        ws.Rows(1).Interior.Color = RGB(173, 216, 230)
        
        ' --- 列幅自動調整 ---
        ws.Columns.AutoFit
        
        ' --- 保存 ---
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' --- 「変換後」フォルダーを開く ---
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' --- Excel終了 ---
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

' ===== UTF-8判定関数 =====
Function IsUTF8File(filePath As String) As Boolean
    Dim fNum As Integer
    Dim bytes() As Byte
    Dim i As Long
    Dim b As Byte
    Dim contBytes As Long
    
    IsUTF8File = True ' 仮にUTF-8とする
    fNum = FreeFile
    Open filePath For Binary As #fNum
    If LOF(fNum) = 0 Then
        Close #fNum
        IsUTF8File = False
        Exit Function
    End If
    ReDim bytes(1 To LOF(fNum))
    Get #fNum, , bytes
    Close #fNum
    
    For i = 1 To UBound(bytes)
        b = bytes(i)
        If contBytes = 0 Then
            If b >= &H80 Then
                If (b And &HE0) = &HC0 Then
                    contBytes = 1
                ElseIf (b And &HF0) = &HE0 Then
                    contBytes = 2
                ElseIf (b And &HF8) = &HF0 Then
                    contBytes = 3
                Else
                    IsUTF8File = False
                    Exit Function
                End If
            End If
        Else
            If (b And &HC0) <> &H80 Then
                IsUTF8File = False
                Exit Function
            End If
            contBytes = contBytes - 1
        End If
    Next i
    
    If contBytes <> 0 Then IsUTF8File = False
End Function


■■■■p190プロンプト例

Excel終了時に、新規ブックの保存確認画面が開いてしまいます。確認せずに終了するようにしてください。


■■■■p190コード例（上記プロンプトの出力）

Sub CSVをExcel形式に変換()
    Dim fldr As FileDialog
    Dim folderPath As String
    Dim fileName As String
    Dim wbCSV As Workbook
    Dim ws As Worksheet
    Dim savePath As String
    Dim destFolder As String
    Dim qt As QueryTable
    Dim colCount As Long
    Dim colTypes() As Long
    Dim tempText As String
    Dim fNum As Integer
    Dim bom(1 To 3) As Byte
    Dim isUTF8 As Boolean
    Dim wb As Workbook
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    ' --- フォルダー選択 ---
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    fldr.Title = "CSVファイルがあるフォルダーを選択してください"
    If fldr.Show = -1 Then
        folderPath = fldr.SelectedItems(1)
    Else
        MsgBox "処理をキャンセルしました。", vbInformation
        GoTo EndProc
    End If
    
    ' --- 保存先「変換後」フォルダー作成 ---
    destFolder = folderPath & "\変換後"
    If Dir(destFolder, vbDirectory) = "" Then MkDir destFolder
    
    ' --- CSVファイル取得 ---
    fileName = Dir(folderPath & "\*.csv")
    If fileName = "" Then
        MsgBox "指定フォルダーにCSVファイルがありません。", vbExclamation
        GoTo EndProc
    End If
    
    Do While fileName <> ""
        
        ' --- UTF-8 / Shift_JIS 判定 ---
        isUTF8 = False
        
        ' 1. BOMチェック
        fNum = FreeFile
        Open folderPath & "\" & fileName For Binary As #fNum
        Get #fNum, , bom
        Close #fNum
        If bom(1) = &HEF And bom(2) = &HBB And bom(3) = &HBF Then
            isUTF8 = True
        Else
            ' 2. BOMなしの場合は簡易UTF-8判定
            If IsUTF8File(folderPath & "\" & fileName) Then
                isUTF8 = True
            End If
        End If
        
        ' --- 列数取得（ゼロ落ち防止用）---
        fNum = FreeFile
        Open folderPath & "\" & fileName For Input As #fNum
        Line Input #fNum, tempText
        Close #fNum
        colCount = UBound(Split(tempText, ",")) + 1
        
        ReDim colTypes(1 To colCount)
        Dim i As Long
        For i = 1 To colCount
            colTypes(i) = 2 ' 全列文字列
        Next i
        
        ' --- 新しいブック ---
        Set wbCSV = Workbooks.Add
        Set ws = wbCSV.Sheets(1)
        
        ' --- CSV読み込み ---
        Set qt = ws.QueryTables.Add(Connection:="TEXT;" & folderPath & "\" & fileName, Destination:=ws.Range("A1"))
        With qt
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            If isUTF8 Then
                .TextFilePlatform = 65001 ' UTF-8
            Else
                .TextFilePlatform = 932   ' Shift_JIS
            End If
            .TextFileColumnDataTypes = colTypes
            .Refresh BackgroundQuery:=False
            .Delete
        End With
        
        ' --- 見出し行を水色に ---
        ws.Rows(1).Interior.Color = RGB(173, 216, 230)
        
        ' --- 列幅自動調整 ---
        ws.Columns.AutoFit
        
        ' --- 保存 ---
        savePath = destFolder & "\" & Left(fileName, Len(fileName) - 4) & ".xlsx"
        wbCSV.SaveAs Filename:=savePath, FileFormat:=xlOpenXMLWorkbook
        wbCSV.Close SaveChanges:=False
        
        ' 次のCSVへ
        fileName = Dir
    Loop
    
    ' --- 「変換後」フォルダーを開く ---
    Shell "explorer.exe " & """" & destFolder & """", vbNormalFocus
    
    ' --- 個人用マクロ以外のブックを保存せずに閉じる ---
    For Each wb In Application.Workbooks
        If wb.Name <> "PERSONAL.XLSB" Then
            wb.Close SaveChanges:=False
        End If
    Next wb
    
    ' --- Excel終了 ---
    Application.Quit
    
EndProc:
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

' ===== UTF-8判定関数 =====
Function IsUTF8File(filePath As String) As Boolean
    Dim fNum As Integer
    Dim bytes() As Byte
    Dim i As Long
    Dim b As Byte
    Dim contBytes As Long
    
    IsUTF8File = True ' 仮にUTF-8とする
    fNum = FreeFile
    Open filePath For Binary As #fNum
    If LOF(fNum) = 0 Then
        Close #fNum
        IsUTF8File = False
        Exit Function
    End If
    ReDim bytes(1 To LOF(fNum))
    Get #fNum, , bytes
    Close #fNum
    
    For i = 1 To UBound(bytes)
        b = bytes(i)
        If contBytes = 0 Then
            If b >= &H80 Then
                If (b And &HE0) = &HC0 Then
                    contBytes = 1
                ElseIf (b And &HF0) = &HE0 Then
                    contBytes = 2
                ElseIf (b And &HF8) = &HF0 Then
                    contBytes = 3
                Else
                    IsUTF8File = False
                    Exit Function
                End If
            End If
        Else
            If (b And &HC0) <> &H80 Then
                IsUTF8File = False
                Exit Function
            End If
            contBytes = contBytes - 1
        End If
    Next i
    
    If contBytes <> 0 Then IsUTF8File = False
End Function

