■■■■■■■第4章 11■■■■■■■

■■■■p146プロンプト例

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

＃＃請求書ファイルの保存
・「テンプレート」シートのコピーを保存する
・ファイル名は「請求書」の文字にE3セルの伝票番号を結合したものとする
　例：請求書25090101.xlsx
・ファイルの保存場所は、このファイルと同じフォルダー

＃＃請求書のPDF作成
・「テンプレート」シートをPDFファイルに出力する
・ファイル名は「請求書」の文字にE3セルの伝票番号を結合したものとする
　例：請求書25090101.pdf
・ファイルの保存場所は、このファイルと同じフォルダー

＃＃「テンプレート」シートのクリア
・「テンプレート」シートの以下のセルの値を消去する
　　A3、E3、E4、A7～D14


■■■■p147コード例

Sub 請求書保存とPDF出力とクリア()
    Dim ws As Worksheet
    Dim invoiceNo As String
    Dim filePath As String
    Dim folderPath As String
    Dim newWb As Workbook
    
    ' 対象シート設定
    Set ws = ThisWorkbook.Sheets("テンプレート")
    
    ' 伝票番号取得（E3セル）
    invoiceNo = ws.Range("E3").Value
    If invoiceNo = "" Then
        MsgBox "E3セルに伝票番号が入力されていません。", vbExclamation
        Exit Sub
    End If
    
    ' 保存先フォルダ（このブックと同じフォルダ）
    folderPath = ThisWorkbook.Path & "\"
    
    '----------------------
    ' Excelファイル保存
    '----------------------
    ws.Copy
    Set newWb = ActiveWorkbook
    filePath = folderPath & "請求書" & invoiceNo & ".xlsx"
    Application.DisplayAlerts = False
    newWb.SaveAs Filename:=filePath, FileFormat:=xlOpenXMLWorkbook
    newWb.Close SaveChanges:=False
    Application.DisplayAlerts = True
    
    '----------------------
    ' PDFファイル出力
    '----------------------
    filePath = folderPath & "請求書" & invoiceNo & ".pdf"
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePath, Quality:=xlQualityStandard
    
    '----------------------
    ' テンプレートシートのクリア
    '----------------------
    ws.Range("A3,E3,E4").ClearContents
    ws.Range("A7:D14").ClearContents
    
    MsgBox "ExcelとPDFの保存、およびテンプレートのクリアが完了しました。", vbInformation
End Sub


■■■■p148プロンプト例

保存先に同じ名前のファイルが存在した場合、上書きするかどうかを確認してください。 
　「はい」→ファイルを上書きして処理を実行する
　「いいえ」→ファイルは上書きせず、処理を終了する


■■■■p148コード例

Sub 請求書保存とPDF出力とクリア()
    Dim ws As Worksheet
    Dim invoiceNo As String
    Dim filePathXlsx As String, filePathPdf As String
    Dim folderPath As String
    Dim newWb As Workbook
    
    ' 対象シート
    Set ws = ThisWorkbook.Sheets("テンプレート")
    
    ' 伝票番号取得
    invoiceNo = ws.Range("E3").Value
    If invoiceNo = "" Then
        MsgBox "E3セルに伝票番号が入力されていません。", vbExclamation
        Exit Sub
    End If
    
    ' 保存先フォルダ
    folderPath = ThisWorkbook.Path & "\"
    
    ' 保存ファイルパス
    filePathXlsx = folderPath & "請求書" & invoiceNo & ".xlsx"
    filePathPdf = folderPath & "請求書" & invoiceNo & ".pdf"
    
    ' 上書き確認
    If Dir(filePathXlsx) <> "" Or Dir(filePathPdf) <> "" Then
        If MsgBox("同じ名前のファイルが存在します。上書きしますか？", vbYesNo + vbQuestion, "上書き確認") = vbNo Then
            MsgBox "処理を中止しました。", vbInformation
            Exit Sub
        End If
    End If
    
    '----------------------
    ' Excelファイル保存
    '----------------------
    ws.Copy
    Set newWb = ActiveWorkbook
    Application.DisplayAlerts = False
    newWb.SaveAs Filename:=filePathXlsx, FileFormat:=xlOpenXMLWorkbook
    newWb.Close SaveChanges:=False
    Application.DisplayAlerts = True
    
    '----------------------
    ' PDFファイル出力
    '----------------------
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePathPdf, Quality:=xlQualityStandard
    
    '----------------------
    ' テンプレートシートのクリア
    '----------------------
    ws.Range("A3,E3,E4").ClearContents
    ws.Range("A7:D14").ClearContents
    
    MsgBox "ExcelとPDFの保存、およびテンプレートのクリアが完了しました。", vbInformation
End Sub


■■■■p150プロンプト例

次のような機能を追加してください。

・「請求明細DB」シートのD列～H列に、「テンプレート」シートのA7～E14セルにある明細の値をコピーして追記する
・「請求明細DB」シートのA列に、D列の最下行と同じ行まで、「テンプレート」シートのE3セルにある伝票番号をコピーして追記する
・「請求明細DB」シートのB列に、D列の最下行と同じ行まで、「テンプレート」シートのE4セルにある日付をコピーして追記する
・「請求明細DB」シートのC列に、D列の最下行と同じ行まで、「テンプレート」シートのA3セルにある請求先をコピーして追記する


■■■■p151コード例

Sub 請求書保存とPDF出力とクリア_明細追記付き()
    Dim ws As Worksheet
    Dim wsDB As Worksheet
    Dim invoiceNo As String, invoiceDate As String, invoiceCustomer As String
    Dim filePathXlsx As String, filePathPdf As String
    Dim folderPath As String
    Dim newWb As Workbook
    Dim lastRowDB As Long
    Dim srcData As Variant
    Dim pasteRow As Long
    Dim i As Long
    
    ' 対象シート
    Set ws = ThisWorkbook.Sheets("テンプレート")
    Set wsDB = ThisWorkbook.Sheets("請求明細DB")
    
    ' 伝票番号・日付・請求先取得
    invoiceNo = ws.Range("E3").Value
    invoiceDate = ws.Range("E4").Value
    invoiceCustomer = ws.Range("A3").Value
    
    If invoiceNo = "" Then
        MsgBox "E3セルに伝票番号が入力されていません。", vbExclamation
        Exit Sub
    End If
    
    ' 保存先フォルダ
    folderPath = ThisWorkbook.Path & "\"
    
    ' 保存ファイルパス
    filePathXlsx = folderPath & "請求書" & invoiceNo & ".xlsx"
    filePathPdf = folderPath & "請求書" & invoiceNo & ".pdf"
    
    ' 上書き確認
    If Dir(filePathXlsx) <> "" Or Dir(filePathPdf) <> "" Then
        If MsgBox("同じ名前のファイルが存在します。上書きしますか？", vbYesNo + vbQuestion, "上書き確認") = vbNo Then
            MsgBox "処理を中止しました。", vbInformation
            Exit Sub
        End If
    End If
    
    '----------------------
    ' 請求明細DBへ追記
    '----------------------
    ' A7:E14 のデータを取得
    srcData = ws.Range("A7:E14").Value
    
    ' D列の最終行を取得
    If Application.WorksheetFunction.CountA(wsDB.Range("D:D")) = 0 Then
        lastRowDB = 0
    Else
        lastRowDB = wsDB.Cells(wsDB.Rows.Count, "D").End(xlUp).Row
    End If
    
    ' 貼り付け開始行（明細DBはD列～H列に貼る）
    pasteRow = lastRowDB + 1
    wsDB.Range("D" & pasteRow).Resize(UBound(srcData, 1), UBound(srcData, 2)).Value = srcData
    
    ' A列に伝票番号、B列に日付、C列に請求先を入力
    For i = pasteRow To wsDB.Cells(wsDB.Rows.Count, "D").End(xlUp).Row
        wsDB.Cells(i, "A").Value = invoiceNo
        wsDB.Cells(i, "B").Value = invoiceDate
        wsDB.Cells(i, "C").Value = invoiceCustomer
    Next i
    
    '----------------------
    ' Excelファイル保存
    '----------------------
    ws.Copy
    Set newWb = ActiveWorkbook
    Application.DisplayAlerts = False
    newWb.SaveAs Filename:=filePathXlsx, FileFormat:=xlOpenXMLWorkbook
    newWb.Close SaveChanges:=False
    Application.DisplayAlerts = True
    
    '----------------------
    ' PDFファイル出力
    '----------------------
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePathPdf, Quality:=xlQualityStandard
    
    '----------------------
    ' テンプレートシートのクリア
    '----------------------
    ws.Range("A3,E3,E4").ClearContents
    ws.Range("A7:D14").ClearContents
    
    MsgBox "ExcelとPDFの保存、明細DBへの追記、テンプレートのクリアが完了しました。", vbInformation
End Sub


■■■■p155プロンプト例

テンプレートのコピーを保存する際は、シート状にある図形を削除してください。


■■■■p155コード例

Sub 請求書保存とPDF出力とクリア_明細追記付き()
    Dim ws As Worksheet
    Dim wsDB As Worksheet
    Dim invoiceNo As String, invoiceDate As String, invoiceCustomer As String
    Dim filePathXlsx As String, filePathPdf As String
    Dim folderPath As String
    Dim newWb As Workbook
    Dim lastRowDB As Long
    Dim srcData As Variant
    Dim pasteRow As Long
    Dim i As Long
    Dim shp As Shape
    
    ' 対象シート
    Set ws = ThisWorkbook.Sheets("テンプレート")
    Set wsDB = ThisWorkbook.Sheets("請求明細DB")
    
    ' 伝票番号・日付・請求先取得
    invoiceNo = ws.Range("E3").Value
    invoiceDate = ws.Range("E4").Value
    invoiceCustomer = ws.Range("A3").Value
    
    If invoiceNo = "" Then
        MsgBox "E3セルに伝票番号が入力されていません。", vbExclamation
        Exit Sub
    End If
    
    ' 保存先フォルダ
    folderPath = ThisWorkbook.Path & "\"
    
    ' 保存ファイルパス
    filePathXlsx = folderPath & "請求書" & invoiceNo & ".xlsx"
    filePathPdf = folderPath & "請求書" & invoiceNo & ".pdf"
    
    ' 上書き確認
    If Dir(filePathXlsx) <> "" Or Dir(filePathPdf) <> "" Then
        If MsgBox("同じ名前のファイルが存在します。上書きしますか？", vbYesNo + vbQuestion, "上書き確認") = vbNo Then
            MsgBox "処理を中止しました。", vbInformation
            Exit Sub
        End If
    End If
    
    '----------------------
    ' 請求明細DBへ追記
    '----------------------
    srcData = ws.Range("A7:E14").Value
    
    If Application.WorksheetFunction.CountA(wsDB.Range("D:D")) = 0 Then
        lastRowDB = 0
    Else
        lastRowDB = wsDB.Cells(wsDB.Rows.Count, "D").End(xlUp).Row
    End If
    
    pasteRow = lastRowDB + 1
    wsDB.Range("D" & pasteRow).Resize(UBound(srcData, 1), UBound(srcData, 2)).Value = srcData
    
    For i = pasteRow To wsDB.Cells(wsDB.Rows.Count, "D").End(xlUp).Row
        wsDB.Cells(i, "A").Value = invoiceNo
        wsDB.Cells(i, "B").Value = invoiceDate
        wsDB.Cells(i, "C").Value = invoiceCustomer
    Next i
    
    '----------------------
    ' Excelファイル保存（図形削除付き）
    '----------------------
    ws.Copy
    Set newWb = ActiveWorkbook
    ' 図形を削除
    On Error Resume Next
    For Each shp In newWb.Sheets(1).Shapes
        shp.Delete
    Next shp
    On Error GoTo 0
    
    Application.DisplayAlerts = False
    newWb.SaveAs Filename:=filePathXlsx, FileFormat:=xlOpenXMLWorkbook
    newWb.Close SaveChanges:=False
    Application.DisplayAlerts = True
    
    '----------------------
    ' PDFファイル出力（元シートは図形残す）
    '----------------------
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePathPdf, Quality:=xlQualityStandard
    
    '----------------------
    ' テンプレートシートのクリア
    '----------------------
    ws.Range("A3,E3,E4").ClearContents
    ws.Range("A7:D14").ClearContents
    
    MsgBox "ExcelとPDFの保存（図形削除済み）、明細DBへの追記、テンプレートのクリアが完了しました。", vbInformation
End Sub
