我最近发现可以使用单个命令在范围的每个单元格内设置值,例如:
Worksheet.Range(Worksheet.Cells(Row1, Column1), Worksheet.Cells(Row2, Column2)) = MyMatrix
其中 MyMatrix
是一个二维矩阵,维度为:Row2-Row1 和 Column2-Column1。
显然,如果我对每个单元格应用相同的属性(假设 .Font.Bold
- 当 MyMatrix
是 bool 矩阵时),它不会不起作用:
Worksheet.Range(Worksheet.Cells(Row1, Column1), Worksheet.Cells(Row2, Column2)).Font.Bold = MyMatrix
上面的命令使整个范围“粗体闪烁”几分之一秒,然后什么也没有发生。怎么会这样?
我绝对希望避免 For
循环,因为在我的代码中它花费的时间太长。
更新:即使我用字符串 "normal"
和 "bold"
填充 MyMatrix
,然后写入:
Worksheet.Range(Worksheet.Cells(Row1, Column1), Worksheet.Cells(Row2, Column2)).Font.FontStyle = MyMatrix
我也尝试过(但不起作用):
Worksheet.Range(Worksheet.Cells(Row1, Column1), Worksheet.Cells(Row2, Column2)).Cells.Font.FontStyle = MyMatrix
最佳答案
正如其他答案所说,.Font
属性只能设置为标量值,而不是矩阵,但它可以一次设置批量范围。
解决这个问题的一种方法是构造一个 String
,其中包含对所有应具有某种字体的单元格的单元格引用,而不是一个 True
矩阵和 False
等。然后只需更改该范围的字体即可。例如
Dim strRange as String
strRange = "A1,B7,C3,D1" ' set this in a loop or whatever
Worksheet.Range(strRange).Font.Bold = True
关于vba - Excel VBA - 是否可以通过使用矩阵为范围的每个单元格设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790041/