C# Excel 具有验证和间接的依赖选择列表
C# Excel Dependent Picklist with Validation & Indirect
下面是从 C# 动态创建依赖选项列表的一般尝试。当从 pick1 选择值 'A' 时,pick2 应该显示 SecondaryRangeA 中的值。
这段代码几乎可以工作,但它没有显示 SecondaryRangeA,而是显示文字值 'A'。
pick2.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
XlFormatConditionOperator.xlBetween,
"=INDIRECT(\"A5\")");
当我在导出并修改数据验证后打开 excel 时,它会显示公式。
=INDIRECT("A5")
如果我在 Excel 中手动修改公式以排除引号,它会按预期工作。
=INDIRECT(A5)
当我将代码修改为以下内容时,出现异常。有什么想法吗?
pick2.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
XlFormatConditionOperator.xlBetween,
"=INDIRECT(A5)");
异常:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2146827284
Message=Exception from HRESULT: 0x800A03EC
Source=""
StackTrace:
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Validation.Add(XlDVType Type, Object AlertStyle, Object Operator, Object Formula1, Object Formula2)
at TestExcelValidation.Program.Main(String[] args) in C:\TFS\ExcelInterop\TestExcelValidation\Program.cs:line 44
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
完整示例:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Excel;
namespace TestExcelValidation
{
class Program
{
static void Main(string[] args)
{
string temporaryPath = Path.GetTempPath();
string temporaryFile = Path.GetTempFileName();
Application appl = new Application();
appl.Visible = true;
Workbook workbook = appl.Workbooks.Open(temporaryFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet worksheet = (Worksheet)workbook.Worksheets.Add();
List<string> primaryList = new List<string>();
primaryList.Add("A");
primaryList.Add("B");
List<string> secondaryListA = new List<string>();
secondaryListA.Add("A1");
secondaryListA.Add("A2");
secondaryListA.Add("A3");
List<string> secondaryListB = new List<string>();
secondaryListB.Add("B1");
secondaryListB.Add("B2");
secondaryListB.Add("B3");
Range primaryRange = AddToExcelNamedRange(worksheet, primaryList, 'A', 1, "PrimaryRange");
Range secondaryRangeA = AddToExcelNamedRange(worksheet, secondaryListA, 'B', 1, "A");
Range secondaryRangeB = AddToExcelNamedRange(worksheet, secondaryListB, 'C', 1, "B");
Range pick1 = worksheet.Range["A5"];
pick1.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=PrimaryRange");
Range pick2 = worksheet.Range["A6"];
pick2.Validation.Delete();
pick2.NumberFormat = "Text";
pick2.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=INDIRECT(\"A5\")");
pick2.Validation.InCellDropdown = true;
pick2.Validation.IgnoreBlank = true;
}
private static Range AddToExcelNamedRange(Worksheet worksheet, List<string> primaryList, char col, int row, string rangeName)
{
Range range = worksheet.Range[col.ToString() + row.ToString(), col.ToString() + primaryList.Count().ToString()];
range.Name = rangeName;
foreach (string item in primaryList)
{
worksheet.Cells[row, col - 64] = item;
row++;
}
return range;
}
}
}
至少在 Excel 2007 和 2010 中,不带引号的 =Indirect(A5)
在单元格中使用时计算结果为 #REF。我在想这段代码是如何从 C# 传递的与异常有关(因为它会评估为错误)。此外,在手动创建验证时使用相同的函数也会在 excel 中给出它评估为错误的消息。编辑:虽然我在这里通过更多研究纠正了一些观点。
来自 Indirect() 的预期输入需要 A1 或 R1C1 格式的字符串值,而不是实际的单元格引用。除非,目标 运行ge 是一个单元格引用,例如:A5 是 A1。
根据 MSDN,Indirect() 仅在文件打开且在内存中时计算 MSDN 151323。打开工作簿并更改验证列表并看到它正确评估并不意味着当 C# 中的代码为 运行.
时错误不存在
例如,如果 A5
中的值为 B
,则 =INDIRECT(A5)
与 =INDIRECT("B")
相同,而 =B
则不同有效的公式或单元格引用。
=INDIRECT("A5")
等同于 =A5
I have a workaround, but I want to know why this doesn't work. I'm sure I will run across this again.
这里是英文回答,天知道另外两个在说什么
问题
通过 C#(或 VBA)在 Excel 中使用验证添加级联下拉列表失败,出现 COMException 0x800A03EC。
原因
它不起作用的原因是 source 实际上是空的。
让我告诉你我是如何解决这个问题的。我在 Excel 和 运行 中注入了一个宏:
Range pick1 = worksheet.Range["A5"];
pick1.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=PrimaryRange");
Range pick2 = worksheet.Range["A6"];
StringBuilder sb = new StringBuilder();
sb.Append("Sub InsertCascadingDropDown()" + Environment.NewLine);
sb.Append(" Range(\"A6\").Select" + Environment.NewLine);
sb.Append(" With Selection.Validation" + Environment.NewLine);
sb.Append(" .Delete" + Environment.NewLine);
sb.Append(" .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= xlBetween, Formula1:=\"=INDIRECT(A5)\"" + Environment.NewLine);
sb.Append(" .IgnoreBlank = True" + Environment.NewLine);
sb.Append(" .InCellDropdown = True" + Environment.NewLine);
sb.Append(" .ShowInput = True" + Environment.NewLine);
sb.Append(" .ShowError = True" + Environment.NewLine);
sb.Append(" End With" + Environment.NewLine);
sb.Append("End Sub" + Environment.NewLine);
//You need to add a COM reference to Microsoft Visual Basic for Applications Extensibility for this to work
var xlmodule = workbook.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
xlmodule.CodeModule.AddFromString(sb.ToString());
appl.Run("InsertCascadingDropDown");
当宏执行添加验证的行时,这会导致 运行 时间错误“1004”:
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=INDIRECT(A5)"
所以这让我相信 selection 对象没有定义(或者更确切地说它是空的,取决于你如何解释这个词 选择).
解决方案
我尝试了这个并最终停止了代码控制并在我发现这个时手动添加了验证:
源当前评估为错误。
selection 对象不为空是确凿证据,A5 下拉列表的 selection/value 实际上是空的!
添加级联下拉列表需要其父级有值!
这就是您需要做的所有事情:
pick1.Value2 = "A"; //< set the parent to have a value
pick2.Validation.Delete(); //<- this is not really needed, unless you run this again
pick2.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=INDIRECT(A5)");
下面是从 C# 动态创建依赖选项列表的一般尝试。当从 pick1 选择值 'A' 时,pick2 应该显示 SecondaryRangeA 中的值。
这段代码几乎可以工作,但它没有显示 SecondaryRangeA,而是显示文字值 'A'。
pick2.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
XlFormatConditionOperator.xlBetween,
"=INDIRECT(\"A5\")");
当我在导出并修改数据验证后打开 excel 时,它会显示公式。
=INDIRECT("A5")
如果我在 Excel 中手动修改公式以排除引号,它会按预期工作。
=INDIRECT(A5)
当我将代码修改为以下内容时,出现异常。有什么想法吗?
pick2.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
XlFormatConditionOperator.xlBetween,
"=INDIRECT(A5)");
异常:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2146827284
Message=Exception from HRESULT: 0x800A03EC
Source=""
StackTrace:
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Validation.Add(XlDVType Type, Object AlertStyle, Object Operator, Object Formula1, Object Formula2)
at TestExcelValidation.Program.Main(String[] args) in C:\TFS\ExcelInterop\TestExcelValidation\Program.cs:line 44
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
完整示例:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Excel;
namespace TestExcelValidation
{
class Program
{
static void Main(string[] args)
{
string temporaryPath = Path.GetTempPath();
string temporaryFile = Path.GetTempFileName();
Application appl = new Application();
appl.Visible = true;
Workbook workbook = appl.Workbooks.Open(temporaryFile, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet worksheet = (Worksheet)workbook.Worksheets.Add();
List<string> primaryList = new List<string>();
primaryList.Add("A");
primaryList.Add("B");
List<string> secondaryListA = new List<string>();
secondaryListA.Add("A1");
secondaryListA.Add("A2");
secondaryListA.Add("A3");
List<string> secondaryListB = new List<string>();
secondaryListB.Add("B1");
secondaryListB.Add("B2");
secondaryListB.Add("B3");
Range primaryRange = AddToExcelNamedRange(worksheet, primaryList, 'A', 1, "PrimaryRange");
Range secondaryRangeA = AddToExcelNamedRange(worksheet, secondaryListA, 'B', 1, "A");
Range secondaryRangeB = AddToExcelNamedRange(worksheet, secondaryListB, 'C', 1, "B");
Range pick1 = worksheet.Range["A5"];
pick1.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=PrimaryRange");
Range pick2 = worksheet.Range["A6"];
pick2.Validation.Delete();
pick2.NumberFormat = "Text";
pick2.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=INDIRECT(\"A5\")");
pick2.Validation.InCellDropdown = true;
pick2.Validation.IgnoreBlank = true;
}
private static Range AddToExcelNamedRange(Worksheet worksheet, List<string> primaryList, char col, int row, string rangeName)
{
Range range = worksheet.Range[col.ToString() + row.ToString(), col.ToString() + primaryList.Count().ToString()];
range.Name = rangeName;
foreach (string item in primaryList)
{
worksheet.Cells[row, col - 64] = item;
row++;
}
return range;
}
}
}
至少在 Excel 2007 和 2010 中,不带引号的 =Indirect(A5)
在单元格中使用时计算结果为 #REF。我在想这段代码是如何从 C# 传递的与异常有关(因为它会评估为错误)。此外,在手动创建验证时使用相同的函数也会在 excel 中给出它评估为错误的消息。编辑:虽然我在这里通过更多研究纠正了一些观点。
来自 Indirect() 的预期输入需要 A1 或 R1C1 格式的字符串值,而不是实际的单元格引用。除非,目标 运行ge 是一个单元格引用,例如:A5 是 A1。
根据 MSDN,Indirect() 仅在文件打开且在内存中时计算 MSDN 151323。打开工作簿并更改验证列表并看到它正确评估并不意味着当 C# 中的代码为 运行.
时错误不存在例如,如果 A5
中的值为 B
,则 =INDIRECT(A5)
与 =INDIRECT("B")
相同,而 =B
则不同有效的公式或单元格引用。
=INDIRECT("A5")
等同于 =A5
I have a workaround, but I want to know why this doesn't work. I'm sure I will run across this again.
这里是英文回答,天知道另外两个在说什么
问题
通过 C#(或 VBA)在 Excel 中使用验证添加级联下拉列表失败,出现 COMException 0x800A03EC。
原因
它不起作用的原因是 source 实际上是空的。
让我告诉你我是如何解决这个问题的。我在 Excel 和 运行 中注入了一个宏:
Range pick1 = worksheet.Range["A5"];
pick1.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=PrimaryRange");
Range pick2 = worksheet.Range["A6"];
StringBuilder sb = new StringBuilder();
sb.Append("Sub InsertCascadingDropDown()" + Environment.NewLine);
sb.Append(" Range(\"A6\").Select" + Environment.NewLine);
sb.Append(" With Selection.Validation" + Environment.NewLine);
sb.Append(" .Delete" + Environment.NewLine);
sb.Append(" .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= xlBetween, Formula1:=\"=INDIRECT(A5)\"" + Environment.NewLine);
sb.Append(" .IgnoreBlank = True" + Environment.NewLine);
sb.Append(" .InCellDropdown = True" + Environment.NewLine);
sb.Append(" .ShowInput = True" + Environment.NewLine);
sb.Append(" .ShowError = True" + Environment.NewLine);
sb.Append(" End With" + Environment.NewLine);
sb.Append("End Sub" + Environment.NewLine);
//You need to add a COM reference to Microsoft Visual Basic for Applications Extensibility for this to work
var xlmodule = workbook.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
xlmodule.CodeModule.AddFromString(sb.ToString());
appl.Run("InsertCascadingDropDown");
当宏执行添加验证的行时,这会导致 运行 时间错误“1004”:
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=INDIRECT(A5)"
所以这让我相信 selection 对象没有定义(或者更确切地说它是空的,取决于你如何解释这个词 选择).
解决方案
我尝试了这个并最终停止了代码控制并在我发现这个时手动添加了验证:
源当前评估为错误。
selection 对象不为空是确凿证据,A5 下拉列表的 selection/value 实际上是空的!
添加级联下拉列表需要其父级有值!
这就是您需要做的所有事情:
pick1.Value2 = "A"; //< set the parent to have a value
pick2.Validation.Delete(); //<- this is not really needed, unless you run this again
pick2.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=INDIRECT(A5)");