VBA 如何使用全局数组 - 它不会从函数返回数据



我有一个全局数组-我在声明中声明它

Public iPick1() As Variant
Public count6 as Long 
Sub MainMacro()
for i=1 to count2
If <something> Then 
count6=count6+1
'....some code 
call AddiPick1(i) 'here I call a function to add the array 
End If
next i 
For a=1 To count6
Rows(iPick1(a)).Delete'here is an error 
Next a
End Sub 

和一个函数,在阵列中添加数据

Function AddiPick1(ByVal ln As Integer)
Dim mark As Integer, u As Long
mark = 0
For u = 1 To count6
If iPick1(u) = ln Then mark = 1
Next u
If mark = 0 Then
count6 = count6 + 1
ReDim Preserve iPick1(count6)
iPick1(count6) = ln
End If
AddiPick1 = iPick1
End Function

但是数组超出了范围。怎么了?

我不明白为什么我不能直接更改任何子或函数中的公共数组,因为全局数组和变量就是为此而创建的。如果有人能解释为什么直接更改适用于全局变量,而我在全局数组中失败了,请回答。

但我有一个方法可以更改函数中的数组并将其返回到sub。只需要将数组作为参数byRef发送就可以像一样工作

Public test()
Public c
Sub testarray()
For i = 1 To 5
c = c + 1
Call test1(test)
Debug.Print test(i)
Next i
End Sub
Function test1(ByRef test)
ReDim Preserve test(c)
test(c) = c
End Function

相关内容

  • 没有找到相关文章

最新更新