通过名称而不是“坐标”访问 Excel 单元格像A1一样
我有一个 Excel 工作表,我在其中命名了必须从代码中填充的单元格。 命名字段的原因是客户可以重新排列单元格。
为了更清楚一点:我使用下面显示的字段来命名单元格。
我现在的问题是,我不知道如何使用 Office 互操作从 C# 处理这些字段。
Range r = Sheet.get_Range("M_Leitung", Type.Missing);
不起作用。由于我没有定义任何范围,只是必须在其中插入值的单个单元格,因此我需要一个返回指定单元格的函数。
I have an Excel Sheet where I've named the cells I have to fill from my code.
The reason for the named fields is that the customer has the possibility to re-arrange the cells.
To make it a little clearer: I used the field shown below to name the cells.
My problem is now that I have no idea how to address these fields from C# using office interop.
Range r = Sheet.get_Range("M_Leitung", Type.Missing);
doesn't work. Since I don't have any ranges defined, just single cells where I have to insert the values, I'd need a function that returns the named cell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚模拟了您的场景,下面的代码就像一个魅力(我在sheet2中将A1标记为M_Leitung):
编辑:更新的代码-当您有多个工作表时,您需要在工作簿范围内引用名称,这将返回完全限定的地址(因此生成的范围知道从哪个工作表中选择地址)
请注意,当您重命名单元格时,您会自动创建一个命名范围。如果您创建了一个 A1:B1 范围并选择了它。 Excel 会向您显示该角标签中的命名范围,而不是地址,这证明它是双向的。
华泰
I just simulated your scenario and the following code worked like a charm (where I labeled A1 in sheet2 as M_Leitung):
Edit: updated code - When you have multiple sheets, you need to refer the names at workbook scope which will return fully qualified address (and hence the resulting range knows which sheet to pick the address from)
Note that you do create a named range automatically when you rename a cell. If you created a range of say A1:B1 and you selected that. Excel would show you the named range in that corner label rather than the addresses which proves it works both ways.
HTH
Excel 中定义的名称具有范围,可以是工作簿或工作表(即全局或本地)。像您所做的那样输入它们会将它们创建为工作簿范围。使用名称管理器检查范围。
使用名称和名称RefersToRange 属性,而不是 Range 来访问它们。语法略有不同:
工作簿范围:
Workbook.Names("M_Leitung").RefersToRange.Value
工作表范围:
Workbook.Sheet.Names("M_Leitung").RefersToRange.Value
code>这样做的原因是您可以在不同的工作表上创建相同的名称。
Defined Names in Excel have scope, either Workbook or Sheet (ie Global or Local). Typing them in like you've done creates them as Workbook scope. Use the Name Manager to check scope.
Use the Names & RefersToRange properties, not Range to access them. The syntax is slightly different:
Workbook scope:
Workbook.Names("M_Leitung").RefersToRange.Value
Worksheet scope:
Workbook.Sheet.Names("M_Leitung").RefersToRange.Value
The reason for this is so you can create the same Name on different sheets.
上面的代码打开一个文件并从工作簿中获取值并更新范围。我认为这会解决问题。
Above code open a file and get the value from workbook and update the range. I think this will solve the problem.