首页 > 解决方案 > Excel VBA - 单元格()参数:传入整数或字符串之间的效率有什么区别?

问题描述

如果您曾经在 Excel VBA 中使用过单元格,您可能已经像这样传递了整数值:

Cells(2, 3)

这是对单元格 C2 的引用。许多人不知道的是,您可以选择为第二个参数/参数传入一个字符串,如下所示:

Cells(2, "C")

我的问题是:效率有什么不同吗?我在 Microsoft 文档中没有找到任何关于此的内容,但我猜测该字符串在运行时被转换为整数或 long,这意味着性能略有不同(更快地传递整数)。

标签: excelvba

解决方案


确实很容易测试,蒂姆。

Sub Test()
    Dim value
    Dim n As Long, t As Double

    Debug.Print "Number of Iterations: "; FormatNumber(Rows.Count, 0)
    Debug.Print "Cells(n, 3)",
    t = Timer
    For n = 1 To Rows.Count
        value = Cells(n, 3)
    Next
    Debug.Print "Time in Seconds: "; Round(Timer - t, 4)

    Debug.Print "Cells(n, ""C"")",
    t = Timer
    For n = 1 To Rows.Count
        value = Cells(n, "C")
    Next
    Debug.Print "Time in Seconds: "; Round(Timer - t, 4)
End Sub

即时窗口截图


推荐阅读