【发布时间】:2015-05-13 09:18:10
【问题描述】:
我正在使用 VSTO 在 C# 中开发 Excel 插件。在这个插件中,我创建了一些样式并将它们添加到当前工作簿中。一切正常,直到我尝试为我的风格设置一些边界。
这是我使用的代码:
var style = workbook.styles.Add("My style");
style.IncludeAlignment = false;
style.IncludeFont = false;
style.IncludeNumber = false;
style.IncludeProtection = false;
style.IncludePatterns = false;
style.IncludeBorder = true;
foreach (XlBordersIndex borderIndex in new[] {
XlBordersIndex.xlEdgeLeft,
XlBordersIndex.xlEdgeRight,
XlBordersIndex.xlEdgeTop,
XlBordersIndex.xlEdgeBottom })
{
style.Borders[borderIndex].LineStyle = XlLineStyle.xlContinuous;
}
我希望这段代码创建一个设置了四个边框的样式,但似乎只设置了左边缘(我可以通过在循环后从调试器中查看样式对象,并在 Excel 中通过编辑“我的风格”)。
我尝试录制一个 VBA 宏来查看 Excel 生成的代码,我得到了这个:
ActiveWorkbook.Styles.Add Name:="My style"
With ActiveWorkbook.Styles("My style")
.IncludeNumber = False
.IncludeFont = False
.IncludeAlignment = False
.IncludeBorder = True
.IncludePatterns = False
.IncludeProtection = False
End With
With ActiveWorkbook.Styles("My style").Borders(xlLeft)
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlRight)
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlTop)
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
With ActiveWorkbook.Styles("My style").Borders(xlBottom)
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
此宏按预期工作。我注意到它使用xlTop、xlLeft 等而不是xlEdgeTop、xlEdgeLeft,但我找不到关于这些常量的任何文档,并且它们在VSTO 枚举XlBordersIndex 中不可用。根据我的发现,似乎后者代表范围的边缘,而前者代表每个单元格的边缘,但我不确定这一点,我认为在谈论样式时差异没有多大意义,这适用于单细胞 AFAICT。
为什么我的 C# 插件和这个 VBA 宏的行为不同?如何从我的 VSTO 代码创建带边框的样式?
【问题讨论】:
-
我刚发现这个问题,好像在说同样的问题:Excel range Style: specifying Borders via VSTO doesn't work。
-
见:msdn.microsoft.com/en-us/library/… xlBottom = -4107 xlLeft = -4131 xlRight = -4152 xlTop = -4160
-
你必须处理所有的边界吗?我仅使用 VBA 使用此方法来获取单元格周围的边框:stackoverflow.com/questions/13121425/…