/// <summary> /// Set a given defined name. If it doesn't exist, a new defined name is created. If it exists, then the existing defined name is overwritten. /// </summary> /// <param name="Name">Name of defined name. Note that it cannot be a valid cell reference such as A1. It also cannot start with "_xlnm" because it's reserved.</param> /// <param name="Text">The reference/content text of the defined name. For example, Sheet1!$A$1:$C$3</param> /// <param name="Comment">Comment for the defined name.</param> /// <param name="Scope">The name of the worksheet that the defined name is effective in.</param> /// <returns>True if the given defined name is created or an existing defined name is overwritten. False otherwise.</returns> public bool SetDefinedName(string Name, string Text, string Comment, string Scope) { Name = Name.Trim(); if (SLTool.IsCellReference(Name)) { return(false); } // these are reserved names if (Name.StartsWith("_xlnm")) { return(false); } if (Text.StartsWith("=")) { if (Text.Length > 1) { Text = Text.Substring(1); } else { Text = "\"=\""; } } uint?iLocalSheetId = null; for (int i = 0; i < slwb.Sheets.Count; ++i) { if (slwb.Sheets[i].Name.Equals(Scope, StringComparison.OrdinalIgnoreCase)) { iLocalSheetId = (uint)i; break; } } bool bFound = false; SLDefinedName dn = new SLDefinedName(Name); dn.Text = Text; if (Comment != null && Comment.Length > 0) { dn.Comment = Comment; } if (iLocalSheetId != null) { dn.LocalSheetId = iLocalSheetId.Value; } foreach (SLDefinedName d in slwb.DefinedNames) { if (d.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)) { bFound = true; d.Text = Text; if (Comment != null && Comment.Length > 0) { d.Comment = Comment; } break; } } if (!bFound) { slwb.DefinedNames.Add(dn); } return(true); }