Last active
March 22, 2024 13:32
-
-
Save ncalm/0d96ab7143be25c360f0e1cdd8204b79 to your computer and use it in GitHub Desktop.
This gist demonstrates how to set protection options in Office Scripts for Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function main(workbook: ExcelScript.Workbook) { | |
const activeSheet = workbook.getActiveWorksheet() | |
// Returns an object representing the worksheet's protection | |
const activeSheetProtection = activeSheet.getProtection() | |
// Protect the sheet according to preferred options (password as 2nd arg is optional) | |
// This line uses the ternary operator. The protect call is only used if the getProtected() call returns false | |
activeSheetProtection.getProtected() || activeSheetProtection.protect(getSheetProtectionOptionsObject()) | |
// Pauses protection for the current user's session (only in Excel online as of 2024-03-21) | |
activeSheetProtection.pauseProtection() | |
// (Change some things in the worksheet) | |
// Resumes protection for the current user's session (only in Excel online as of 2024-03-21) | |
activeSheetProtection.resumeProtection() | |
} | |
function getSheetProtectionOptionsObject(): ExcelScript.WorksheetProtectionOptions { | |
/* Protection options are boolean except for selectionMode | |
which uses the ExcelScript.ProtectionSelectionMode enum | |
https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.protectionselectionmode?view=office-scripts?wt.mc_id=MVP_310565 | |
ExcelScript.ProtectionSelectionMode.none means "Selection is not allowed for any cells" | |
ExcelScript.ProtectionSelectionMode.normal means "Selection is allowed for all cells" | |
ExcelScript.ProtectionSelectionMode.unlocked means "Selection is allowed only cells that are unlocked" | |
*/ | |
return { | |
allowAutoFilter: true, | |
allowDeleteColumns: false, | |
allowDeleteRows: false, | |
allowFormatRows: false, | |
selectionMode: ExcelScript.ProtectionSelectionMode.unlocked, | |
allowEditObjects: false, | |
allowEditScenarios: false, | |
allowInsertRows: false, | |
allowFormatColumns: false, | |
allowFormatCells: false, | |
allowInsertColumns: false, | |
allowSort: true, | |
allowInsertHyperlinks: false, | |
allowPivotTables: false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment