簡體   English   中英

VBA 將數組傳遞給 function 並返回

[英]VBA Passing an array to a function and back

我已經開始復習 cpearson 關於傳遞和返回 arrays 的文章,我對細節有點迷失了。 以下內容無效,並由論文確認。 似乎我可以通過循環通過 arrays 將每個元素設置為等於另一個數組中的元素來解決問題。 如何使用 function 執行此操作?

Sub test()

    Dim Arr() as Variant
    Dim CurrDoc as Word.Document

    ReDim Arr(0 to 39, 0 to 1)

    Arr() = FillArr(CurrDoc, Arr())

End Sub

Function FillArr(CurrentDocument As Word.Document, CurrentArray() As Variant) As Variant

    j = 1

    For Each chk In CurrentDocument.ContentControls

        If chk.Type = 8 Then

            CurrentArray(j, 1) = chk.Title
            CurrentArray(j, 2) = chk.Checked

            j = j + 1

        End If

    Next chk

FillArr() = CurrentArray()

End Function

我個人會以不同的方式處理這個問題。

返回標題的 function 的有用性和所有“復選框”類型內容控件的“已檢查”state 的有用性低於 ZC1C425268E68385D1AB5074C17A94F14 的某些類型的內容控件的有用性。 原因如下:

調用 function 的代碼已經知道它想要使用TitleChecked ,因此當它獲取ContentControl實例數組而不是字符串和布爾值的多維數組時,什么都不會丟失。 但是當調用代碼想要操作復選框時,“字符串和布爾值”方法就達不到要求了。

在這個假設下,我們可以去掉數組的一維,得到一個可以在不同場景中重復使用的 function。

我們也不需要任何數組傳遞。 只需構建數組並返回它:

Function FindControls(Doc As Word.Document, ControlType As WdContentControlType) As Variant
    Dim cct As Variant, i As Integer

    ' figure out how many matching controls there are and allocate an array
    For Each cct In Doc.ContentControls
        If cct.Type = ControlType Then i = i + 1
    Next cct
    ReDim cctArray(i - 1)

    ' save references to matching controls in array
    i = 0
    For Each cct In Doc.ContentControls
        If cct.Type = ControlType Then
            Set cctArray(i) = cct
            i = i + 1
        End If
    Next cct

    FindControls = cctArray
End Function

現在我們可以很自然地在調用代碼中使用它:

Dim c As Variant

For Each c In FindControls(ActiveDocument, wdContentControlCheckbox)
    Debug.Print c.Title, c.Checked
Next

我不想制作一個完全匹配你的單詞文檔,但你可以通過函數傳遞 arrays。 我要用隨機字符填充我的。

Sub test()
    Dim arr() As Variant
    ReDim arr(1 To 40, 1 To 2)

    arr() = fillarr(arr())

    Dim i As Long

    For i = 1 To 40
        Debug.Print i, arr(i, 1)
        Debug.Print i & "* 5", arr(i, 2)
    Next i
End Sub

Function fillarr(currentarr() As Variant) As Variant
    Dim j As Long

    For j = 1 To 40
        currentarr(j, 1) = Chr(j + 64)
        currentarr(j, 2) = Chr(j * 5)
    Next j

    fillarr = currentarr
End Function

實際上有一個隱含by ref因為在 VBA arrays 總是通過引用傳遞,所以你實際上並不需要 function 來做到這一點,但你可以在這里更清楚地看到:

Sub test()
    Dim arr() As Variant
    ReDim arr(1 To 40, 1 To 2)

    fillarr arr() 'no value set

    Dim i As Long

    For i = 1 To 40
        Debug.Print i, arr(i, 1)
        Debug.Print i & "* 5", arr(i, 2)
    Next i
End Sub

Sub fillarr(currentarr() As Variant)
    Dim j As Long

    For j = 1 To 40
        currentarr(j, 1) = Chr(j + 64)
        currentarr(j, 2) = Chr(j * 5)
    Next j

    'Note the lack of return
End Sub

暫無
暫無

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

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