gpt4 book ai didi

vba - VBA 变量何时实例化

转载 作者:行者123 更新时间:2023-12-04 18:31:07 25 4
gpt4 key购买 nike

我很犹豫要问,但我找不到任何文档 VBA .

相关(但我不认为是骗子):

  • C++ When are global variables created?
  • In Java, should variables be declared at the top of a function, or as they're needed?
  • C++ Declare variables at top of function or in separate scopes?
  • 和最可能相关的 When are a module's variables in VB.NET instantiated?
  • 我也看了C# on programmers.SE .

  • 我想我使用“实例化”这个词是正确的,但如果我错了,请纠正我。实例化是在创建变量并为其分配所需的资源时?所以在 VBA 中,我看到了两种方法。

    一切都在顶部!
    Public Sub ToTheTop()
    Dim var1 As Long
    Dim var2 As Long
    Dim var3 As Long

    var1 = 10
    var2 = 20
    var3 = var1 + var1
    Debug.Print var3
    End Sub

    或接近使用
    Public Sub HoldMeCloser()
    Dim var1 As Long
    var1 = 10
    Dim var2 As Long
    var2 = 20
    Dim var3 As Long

    var3 = var1 + var1
    Debug.Print var3
    End Sub

    我喜欢把它们放在更接近使用的地方,以便更容易记住它们是什么,而其他人可能想要让它们全部消失。那是个人喜好。

    但是,我想我记得在某处读到过 VBE 通过子/函数并在继续执行其他任何操作之前实例化所有变量。这表明在 VBA 中没有正确的方法来做到这一点,因为变量作用域不会改变。不是 Private 中的范围对比 Public .

    而在其他语言中,范围似乎可以根据位置而改变,因此有一个最佳实践。

    我一直在寻找这个文档一段时间了,但是我使用的任何词都没有指向正确的方向,或者文档不存在。

    最佳答案

    根据reference documentation ,

    When a procedure begins running, all variables are initialized. A numeric variable is initialized to zero, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with the character represented by the ASCII character code 0, or Chr(0). Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

    When you declare an object variable, space is reserved in memory, but its value is set to Nothing until you assign an object reference to it using the Set statement.


    这意味着无论变量声明在哪里声明,它的空间/内存都是在进入过程时分配的。

    关于vba - VBA 变量何时实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751682/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com