
[英]“Excel has stopped working” when using VBA macro with on change event
[英]Using VBA in Excel - Static variable not retained when Multipage object has change event (changing pages)
我无法在 Excel 用户表单中丢失 static 个变量。
我一直在为 excel 做例程。我是一个(非常)新手编码器。
我正在尝试将单元格范围填充到数组中。 我已经能够毫无问题地做到这一点。
但是,当我尝试将数组存储为 *static * 变量时,只要我希望它保留,变量就不会保留。
我认为问题发生在多页中选择另一个页面时,static 变量被清除。
代码是这样的:
Sub UserForm_Initialize ()
static myArray () as variant
dim myRange as range
set myRange = [namedrange]
myArray=myRange
msgbox myArray(0,0) 'this works fine
call OtherSub
end sub
sub OtherSub ()
msgbox myArray(0,0) 'this returns a blank
end sub
第一个子代码很好地显示了数组元素。 第二个子数组元素为空。
我努力了:
我知道我可以只将数据写入单元格范围,但这会破坏目的。 我希望避免从工作表中读取大 arrays 的多个实例。
这可能会解释得更清楚一些。 将 MyArray 移到过程之外会将其 scope 设置为模块级别,使其可通过该模块中的其他子程序使用。 您通常希望将变量的 scope 保持在所需的最低级别。 另一种选择是将您的变量作为参数传递给您的其他过程。
Option Explicit
Dim MyArray() As Variant ' Private Module Level Scope
Public ExampleVariable As String ' Public Module Level Scope (Not required, just showing an example.)
Sub UserForm_Initialize()
Dim myRange As Range ' Procedure Level Scope
Set myRange = [namedrange]
MyArray = myRange
MsgBox MyArray(0, 0) 'this works fine
Call OtherSub
End Sub
Sub OtherSub()
MsgBox MyArray(0, 0) 'this returns a blank
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.