当前位置:网站首页>A method and implementation of using VSTO to prohibit excel cell editing

A method and implementation of using VSTO to prohibit excel cell editing

2022-07-06 15:09:00 Nonsense

Ideas

  • Whenever the protected cell is selected , Make it unselected
  • The protected cell cannot get the focus , That is, you cannot edit

Realization

  • Implement logic that cannot be selected
        /** *  When protected range By selected When , mandatory select To a certain goal range * protectedSheet  The protected sheet * currentSheet  Current sheet * protectedRanges  The protected range list  * currentRange  At present select Of range * destinationRange  The goal is range, Be preposed select Of range */
        public static void ForceSelect(string protectedSheet, Excel.Worksheet currentSheet,
            List<string> protectedRanges, string currentRange, string destinationRange)
        {
    
            if (currentSheet.Name.Equals(protectedSheet) && protectedRanges.Contains(currentRange))
            {
    
                currentSheet.Range[destinationRange].Select();
            }
        }
  • register “SheetSelectionChange” event
        /** *  Registration events : Implementation cells are not editable  */
        public void RegisterSheetSelectionChange()
        {
    
             ExcelApp.SheetSelectionChange += ExcelApp_SheetSelectionChange;
        }

        private void ExcelApp_SheetSelectionChange(object Sh, Excel.Range Target)
        {
    
            Excel.Worksheet sheet = (Excel.Worksheet)Target.Parent;
            string address = Target.Address.Replace("$", "");
            List<string> protectedRanges = new List<string>();
            protectedRanges.Add("B1");
            protectedRanges.Add("B2");
            WorksheetHandler.ForceSelect("sheetName", sheet, protectedRanges, address, "A1");
        }
原网站

版权声明
本文为[Nonsense]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131323124778.html