使用非默认值在VBA中初始化静态变量

时间:2014-10-17 11:40:50

标签: vba static vb6

VBA中的静态变量非常简单:

Public Sub foo()
    Static i As Integer
    i = i + 1
    Debug.Print i
End Sub

输出(多次调用时):

1
2
3
...

问题是,VBA不支持在与声明相同的行上初始化变量(不计算使用:将两行放在一行上):

Public Sub foo()
    Dim i As Integer = 5 'won't compile!

    Dim j As Integer
    j = 5 'we have to do this instead
End Sub

这与静态变量发生冲突:

Public Sub foo()
    Static i As Integer 'we can't put an initial value here...
    i = 5 'so this is how we'd usually initialize it, but...
    i = i + 1
    Debug.Print i
End Sub

你可能会看到会发生什么 - 每次调用foo时变量所做的第一件事就是将其自身设置为5.输出:

6
6
6
...

如何将VBA中的静态变量初始化为默认值以外的值?或者这只是VBA丢球?

3 个答案:

答案 0 :(得分:8)

如果你想保持静态语义而不是切换到全局,那么一种方法是嗅探默认值,然后设置初始条件:

Static i As Integer
if (i = 0) then i = 5

更安全的替代方案可能是

Static i As Variant
if isempty(i) then i = 5

Public Sub foo(optional init as boolean = false)
    Static i As Integer
    if init then
      i = 5
      exit sub
    endif

您可能还可以使用默认属性创建一个类并使用class_initialize,但这可能有点过于繁琐。

答案 1 :(得分:3)

我在VB6中遇到了同样的问题,它完全相同,我最喜欢getMemberGroups

Sub initstatic ()
  Static Dummy, V, I As Integer, S As String

  ' The code in the following if statement will be executed only once:
  If IsEmpty(Dummy) Then
     ' Initialize the dummy variant, so that IsEmpty returns FALSE for
     ' subsequent calls.
     Dummy = 0

     ' Initialize the other static variables.
     V = "Great"
     I = 7
     S = "Visual Basic"
  End If

  Print "V="; V, "I="; I, "S="; S

  ' Static variables will retain their values over calls when changed.
  V = 7
  I = I + 7
  S = Right$(S, 5)
End Sub

答案 2 :(得分:0)

我使用一个静态布尔值来解决此问题,该布尔值指示您是否是第一次进入该函数。我认为,这种逻辑也应该适用于其他情况

    io.on("connection", socket => {
      console.log("User Connected");

      socket.on("join_room", ({ name, room }) => {
        socket.join(room);

        console.log(name, room);

        console.log(Object.keys(io.sockets.in(room).connected).length);
      });

      socket.on("senddata", ({ socket, data }) => {
        socket.to(room).emit("data", {
          data,
          name: "Hello"
        });
      });

      socket.on("disconnect", () => {
        console.log("User Disconnected");
      });
    });