gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
How can I add this to the WorkSheet close event so that I can clear B3:B12 before the…
- User
How can I add this to the WorkSheet close event so that I can clear B3:B12 before the sheet closes: If Worksheets("Notes").Range("B3:B12")<>"" Then Dim answer As VbMsgBoxComplete answer = MsgBox("Do you want to clear Completed Tasks?", vbQuestion + vbYesNo, "Confirmation") If answer = vbYes Then ThisWorkbook.Sheets("Notes").Range("B3:B12").ClearContents End If End If
- Assistant
To add this code to the Worksheet_Close event, you can follow these steps:
- Right-click on the sheet tab where you want to add the code (e.g., "Notes") and select "View Code." This will open the code window for that worksheet.
- In the code window, locate the dropdown menu at the top-left corner, and select "Worksheet" from the left dropdown list and "BeforeClose" from the right dropdown list. This will create the Worksheet_BeforeClose event.
- Below the generated event code, add the following code:
Private Sub Worksheet_BeforeClose(Cancel As Boolean) If Application.Worksheets("Notes").Range("B3:B12") <> "" Then Dim answer As VbMsgBoxResult answer = MsgBox("Do you want to clear Completed Tasks?", vbQuestion + vbYesNo, "Confirmation") If answer = vbYes Then ThisWorkbook.Sheets("Notes").Range("B3:B12").ClearContents End If End If End Sub- Save the workbook.
Now, when the user tries to close the "Notes" worksheet, it will check if the range B3:B12 is not empty. If it is not empty, it will ask for confirmation before clearing the contents of that range.