如何使用VSTO代码的边框创建样式



我使用VSTO在C#中开发Excel Addin。在此Addin中,我创建了一些样式,并将它们添加到当前的工作簿中。一切正常,直到我尝试在我的风格上设置一些边界。

这是我使用的代码:

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

此宏可以按预期工作。我注意到它使用xlTopxlLeft等。而不是xlEdgeTopxlEdgeLeft,但我找不到有关这些常数的任何文档,并且在VSTO枚举XlBordersIndex中不可用。从我的发现来看,后者似乎代表了范围的边缘,而前者则代表了每个单元的边缘,但是我不确定这一点,我认为在谈论样式,,差异并没有多大意义。适用于单个单元格。

为什么我的C#addin和此VBA宏之间有不同的行为?我如何从VSTO代码中创建带有边框的样式?

根据此讨论,似乎风格边界与范围的边界之间存在差异:后者由XlBordersIndex索引(xlEdgeTopxlEdgeLeft,...),如文档中所述,但前者由ConstantsxlTopxlLeft,...)索引。

,如果我们认为样式适用于单个单元格,而不是范围,这也是有道理的,但这也意味着要访问样式边界,我们必须使用无关常数绕过Borders接口的接口。Anushrudaa在这里提出的这种解决方法似乎有效:

foreach (XlBordersIndex borderIndex in new[] { 
                (XlBordersIndex)Constants.xlLeft, 
                (XlBordersIndex)Constants.xlRight, 
                (XlBordersIndex)Constants.xlTop, 
                (XlBordersIndex)Constants.xlBottom })
{
    style.Borders[borderIndex].LineStyle = XlLineStyle.xlContinuous;
}

最新更新