我是.Net世界的新手。我正在用C#(vsto(为Excel编写一个加载项,我想在其中读取给定Excel工作表中每个单元格中使用的所有字体样式。以下代码有效,
List<string> fontsInSheet = new List<string>();
Excel.Range usedRange = currentSheet.UsedRange;
for (int i = 1; i <= usedRange.Rows.Count; i++)
{
for (int j = 1; j <= usedRange.Columns.Count; j++)
{
Range excelCellRange = currentSheet.Cells[i, j];
if (!(excelCellRange.Font.Name is DBNull) &&(!fontsInSheet.Contains(excelCellRange.Font.Name)))
{
fontsInSheet.Add(excelCellRange.Font.Name);
}
}
}
但不幸的是,如果Excel工作表太大,嵌套的for循环会太慢。因此,是否有更好的解决方案可以更有效地检索使用过的字体样式。提前谢谢。
您可以尝试在之前使用以下属性,并在之后返回它们的值:
Sub OptimizeVBA(enable As Boolean)
Application.Calculation = IIf(enable, xlCalculationManual, xlCalculationAutomatic)
Application.EnableEvents = Not(enable)
Application.ScreenUpdating = Not(enable)
ActiveSheet.DisplayPageBreaks = Not(enable)
End Sub
有关这些属性和其他可能方法的详细信息,请参阅"改进VBA性能指南"。更快的EXCEL VBA文章。
C#代码段,
private void Optimize(Boolean enable)
{
Application.Calculation = enable ? XlCalculation.xlCalculationManual : XlCalculation.xlCalculationAutomatic;
Application.EnableEvents = !enable;
Application.ScreenUpdating = !enable;
GetActiveWorkSheet().DisplayPageBreaks = !enable;
}