簡體   English   中英

VBA:如何從函數傳遞字符串數組

[英]VBA: how to pass a string array from an function

我不能很好地處理數組與函數的結合。 我想在外部函數中編輯字符串數組。 (稍后也用保留重新修改它)但在我的測試中我得到一個錯誤:

 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

你沒有返回你的數組:

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

或如評論所述更改為 sub 並執行 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

通過引用返回數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM