示例#1
0
        /// <summary>
        /// Checks if named range exists in the workbook
        /// </summary>
        /// <param name="workbook">Target workbook</param>
        /// <param name="name">Name of range</param>
        /// <param name="notOnWorksheet">Flags if user wants values unique to workbook scope</param>
        public static bool NamedRangeExists(this Excel.Workbook workbook, string name, bool notOnWorksheet = false)
        {
            // List of named ranges on a worksheet
            var sheetList = new List <string>();

            // List of named ranges in the entire workbook
            var workbookList = workbook.NamedRanges();

            // List of named ranges that exist only on the workbook scope
            var filteredList = new List <string>();

            if (notOnWorksheet == true)
            {
                // Adds all worksheet named ranges to sheet list (removes worksheet identifier i.e. Sheet1!, etc.)
                foreach (Excel.Worksheet sheet in workbook.Worksheets)
                {
                    sheetList.AddRange(sheet.NamedRanges());
                }

                // Only keeps unique workbook named ranges on filtered list
                filteredList = workbookList.Except(sheetList).ToList();
                return(filteredList.Exists(x => x == name));
            }
            else
            {
                return(workbookList.Exists(x => x == name));
            }
        }