2

I have this short piece of code

Public n As Integer

Public Sub Foo()

    For i = 0 To 4

        MyModule.n = MyModule.n + 1

    Next i

End Sub

which is defined in a Module named MyModule. This code is working as expected: After executing for the first time 'MyModule.n' has the value 5. After executing the second time it has the value 10 and so on.

When I extend the code, to add a CommandButton and place it onto the working sheet, the global variable MyModule.n loses it's value on every new call of Foo:

Public n As Integer

Public Sub Foo()

    Dim btn As OLEObject

    For i = 0 To 4

        Set btn = Worksheets("Aufträge").OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
        Left:=122, Top:=321, Width:=30, Height:=30)

        MyModule.n = MyModule.n + 1

    Next i

End Sub

The code seems to work because the command button is created and placed correctly. Why does the global variable reset if executing the second code fragment?

Furthermore I can't place a break point after or inside the For-Loop in the second code fragment. I get the message Can't enter break mode at this time.

4

2 回答 2

9

Based on the search I did & my conclusion is that you can't add controls dynamically to the worksheet and retain the state of variables.

Here is why: Adding a button will force the sheet to goto design mode & hence reset of variables.

Supporting links

  1. http://www.pcreview.co.uk/forums/dynamically-adding-activex-controls-via-vba-kills-global-vba-heap-t3763287p2.html

  2. https://web.archive.org/web/20101215134333/http://support.microsoft.com/kb/231089 (originally //support.microsoft.com/kb/231089)

于 2012-09-02T17:04:05.587 回答
0

对于第一个示例,您不需要使用 for next 循环。你为什么不这样做:

Public n As Integer

Public Sub Foo()

    MyModule.n = 5


End Sub

这将在一次操作中完成。

在第二个示例中,您没有添加一个按钮,而是添加了 5 个按钮。查看“For Next”的帮助。

于 2012-09-02T16:09:35.830 回答