简体   繁体   中英

VBA: how to pass a string array from an function

I can't handle the array in combination with an function very well. i want to edit an string array in an external function. (also redim it later with preserve) But in my test i get an error:

 Sub test()
        Dim test() As Variant
        Dim testnew() As Variant
        ReDim Preserve test(1 To 4)
        test(1) = "one"
        test(2) = "two"
        test = testfunc(test)
        Debug.Print test(3)
    End Sub
    
Function testfunc(test() As Variant) As Variant
test(3) = "three"
End Function

You are not returning your array:

Sub test()
    Dim test() As Variant
    Dim testnew() As Variant
    ReDim Preserve test(1 To 4)
    test(1) = "one"
    test(2) = "two"
    test = testfunc(test)
    Debug.Print test(3)
End Sub
    
Function testfunc(test() As Variant) As Variant
    test(3) = "three"
    testfunc = test
End Function

or as the comments have stated change to sub and do byRef:

Sub test()
    Dim test() As Variant
    Dim testnew() As Variant
    ReDim Preserve test(1 To 4)
    test(1) = "one"
    test(2) = "two"
    testfunc test
    Debug.Print test(3)
End Sub
    
Sub testfunc(ByRef test() As Variant)
    test(3) = "three"
End Sub

Return the array by reference :

Public Sub test()

    Dim test() As Variant
    Dim testnew() As Variant

    ReDim Preserve test(1 To 4)
    test(1) = "one"
    test(2) = "two"
    testfunc test

    Debug.Print test(3)
    
End Sub
    
Public Sub testfunc(test() As Variant)
    
    test(3) = "three"
    
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM