Home > database >  VBA How to work with global arrays- it doesn't return data from function
VBA How to work with global arrays- it doesn't return data from function

Time:10-05

I've got a global array - I declare it in declarations

    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 

and a function, adding data in the array

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

But the array is out of range. What's wrong?

CodePudding user response:

I haven't understood why can't I change public array in any sub or function directly - because global array and variables are made just for this. If anybody can explain me why direct change works with global variables and I failed with the global array - please answer.

But I've got a method to change the array in function and return it to sub. Need just to send array as argument byRef to function like this

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
  • Related