在我的循环中(见下面的代码),为什么我不应该打开 ws.Cells.SpecialCells(xlCellTypeFormulas)
引用 Range
对象变量? (基于良好的编码习惯,我们不应该将所有 Range、Worksheet 和 Workbook 对象引用都变成对象变量吗?不管它们是使用一次还是多次使用?)
我确实尝试过成功,但我有这种感觉我不应该,但我不知道为什么这导致我询问具体原因。
Sub FormatAllFormulas()
Dim ws As Worksheet
Dim wsc As Sheets
Set wsc = ActiveWorkbook.Worksheets
For Each ws In wsc
With ws.Cells.SpecialCells(xlCellTypeFormulas)
.Style = "Currency"
.Font.Bold = True
.Interior.Color = 4908260
End With
Next ws
End Sub
最佳答案
你 是 获得对 Range
的引用变量 - 它只是由 With
持有封锁自己。 5.4.2.21语言规范解释:
The With block variable is classified as a variable and has the same declared type as <expression>.
在运行时,会发生以下情况:
If the value type of the evaluated expression is a class, it is Set-assigned to an anonymous With block variable. Then, <statement-block> is executed. After <statement-block> executes, Nothing is assigned to the anonymous With block variable.
从功能上讲,您示例中的此代码...
For Each ws In wsc With ws.Cells.SpecialCells(xlCellTypeFormulas) .Style = "Currency" .Font.Bold = True .Interior.Color = 4908260 End With Next ws
...与此完全相同:
For Each ws In wsc
Dim WithBlockVariable As Range
Set WithBlockVariable = ws.Cells.SpecialCells(xlCellTypeFormulas)
WithBlockVariable.Style = "Currency"
WithBlockVariable.Font.Bold = True
WithBlockVariable.Interior.Color = 4908260
Set WithBlockVariable = Nothing
Next ws
至于你应该使用哪个,这几乎是一个判断电话。正如评论中指出的,
With
block 可以比局部变量更具可读性。另一个考虑是,由于引用是隐式的,你不能在 With
之后意外使用它。 block 导出。这在您的示例中可能很重要,因为声明的变量始终具有过程范围。这意味着在扩展示例中,您可以使用 WithBlockVariable
在循环之外。所以,如果你不打算在 block 外使用它,你还不如让它 不可能在 block 外使用。最后要注意的一件事(这是人们可能遇到性能问题的地方)是
With
如果您发现自己重复使用多个 .
, block 可以保存取消引用操作在表达式中。例如,如果您在 Font
上设置多个属性。 :With ws.Cells(1, 1)
.Font.Bold = True
.Font.Color = vbRed
.Font.Italic = True
End With
在这种情况下,绝对没有理由明确引用
Font
。 ,但请注意您反复调用 Range.Font
属性(property)。这总是更好:With ws.Cells(1, 1).Font
.Bold = True
.Color = vbRed
.Italic = True
End With
关于excel - 为什么我不应该将某些对象引用转换为对象变量?指导方针是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412341/