ワークブックの保存メソッド (Excel) | Microsoft Learn

この記事では、指定されたワークブックに変更を保存する方法について説明しています。方法は、expression.Saveを使用してワークブックオブジェクトを表すexpressionを指定します。最初にワークブックを保存する場合は、SaveAsメソッドを使ってファイル名を指定します。例として、アクティブなワークブックを保存するコードや、すべてのオープンワークブックを保存してExcelを終了するコードが挙げられています。また、特定のセルにデータがあるか確認するBeforeSaveイベントも紹介されています。

Excel VBA: ワークブックの保存方法

Excel VBA を使用して、ワークブックを保存する方法について解説します。ワークブックをエクスポートしたり変更を保存したりするための基本を学びましょう。

基本的な使い方

ワークブックを保存するには、以下の構文を使用します。

expression.Save

ここでの expressionWorkbook オブジェクトを示す変数です。

注意事項

  1. ワークブックを開く: ワークブックファイルを開くには、Open メソッドを使用します。
  2. ディスクに書き込まずに保存済みとする: ワークブックをディスクに書き込むことなく「保存済み」としてマークするには、Saved プロパティを True に設定します。
  3. ファイル名を指定して保存: 初めてワークブックを保存する際には、SaveAs メソッドを使用してファイル名を指定します。

使用例

以下に、ワークブックを保存するいくつかの例を示します。

アクティブなワークブックを保存

この例では、アクティブなワークブックを保存します。

ActiveWorkbook.Save

開いているすべてのワークブックを保存し、Excelを閉じる

この例では、すべての開いているワークブックを保存し、その後 Microsoft Excel を閉じます。

For Each w In Application.Workbooks
    w.Save
Next w
Application.Quit

セルにデータが存在するかを確認してから保存

この例では、BeforeSave イベントを使用して、特定のセルにデータが含まれているかを確認します。以下のセル(D5, D7, D9, D11, D13, D15)にデータがない場合、ワークブックを保存できません。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    If WorksheetFunction.CountA(Worksheets("Sheet1").Range("D5,D7,D9,D11,D13,D15")) = 0 Then
        MsgBox "指定されたセルにはデータが含まれていません。保存をキャンセルします。"
        Cancel = True
    End If
End Sub

サポートとフィードバック

Office VBA やこのドキュメントに関して質問やフィードバックがある場合は、Office VBA サポートとフィードバックをご覧ください。サポートを受けたり、フィードバックを提供する方法が記載されています。

Excel VBAをマスターして、効率的にワークブックを操作していきましょう。

————-

Workbook.Save method (Excel) | Microsoft Learn

Source link

The article, dated March 30, 2022, discusses how to save changes to a workbook using VBA (Visual Basic for Applications) in Microsoft Excel. The primary syntax for saving a workbook is expression.Save, where expression is a variable representing the Workbook object.

Key points include:

  • To open a workbook, the Open method can be used.
  • You can mark a workbook as saved without writing it to disk by setting its Saved property to True.
  • When saving a workbook for the first time, the SaveAs method should be used to specify a file name.

Examples provided include:

  1. Saving the active workbook using ActiveWorkbook.Save.
  2. Saving all open workbooks and closing Excel in a loop.
  3. Implementing a BeforeSave event to prevent saving the workbook unless specific cells (D5, D7, D9, D11, D13, D15) contain data; if not, an error message will be displayed, and the save is canceled.

The article concludes with a prompt for users to seek support or provide feedback regarding Office VBA documentation.

関連記事