excel - 为什么我不应该将某些对象引用转换为对象变量?指导方针是什么?

标签 excel vba variables

在我的循环中(见下面的代码),为什么我不应该打开 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/

相关文章:

java - 为什么我在初始化实例变量时得到零?

c - 参数变量存储在内存中的什么位置?

Excel VBA : How to find max/min of a range while ignoring error cells

bash - Fortran 的麻烦。我怎样才能制作一个更高效、更简单的界面。也许使用 Bash 脚本或 VBA?

php 将 MySql 导出到 excel 工作表不起作用

javascript - VBA 导航 IE javascript 链接

excel - 使用 VBA 将 CSV 导入 Excel 匹配列标题

vba - 使用自定义 HTML 代码替换 Outlook 下的文本选择的替代方法

java - 如何扫描文件以搜索值

excel - 将 2D 数组转换为 1D 数组