[英]Passing arrays to functions in VBA
我有一個接受數組的過程。 因此我可以傳遞一個數組,如:
Public Sub MySub (Something as String, ByRef Arr() as Variant)
'Stuff
End Sub
Public Sub Test()
Dim Columns() As Variant
Columns = Array(1, 2, 3, 4, 5, 6)
MySub "sth", Columns
End Sub
問題是,當我想內聯進行時
MySub "sth", Array(1, 2, 3, 4, 5, 6)
或者
MySub "sth", Cvar(Array(1, 2, 3, 4, 5, 6))
我收到一個編譯錯誤,提示類型不匹配:需要數組或用戶定義的類型。
如何將內聯數組傳遞給函數?
將數組參數從變體數組更改為僅變體
Public Sub MySub(Something As String, ByRef Arr As Variant)
'Stuff
End Sub
Public Sub Test()
Dim Columns() As Variant
Columns = Array(1, 2, 3, 4, 5, 6)
MySub "sth", Columns
MySub "sth", Array(1, 2, 3, 4, 5, 6)
'both worked in my test
End Sub
我使用 Excel 2013 來運行您的 VBA 代碼,並且沒有類型不匹配錯誤。 例如與子:
Public Sub MySub(Something As String, ByRef Arr() As Variant)
For i = 0 To UBound(Arr)
Debug.Print Arr(i)
Next i
End
End Sub
我得到了在即時窗口中打印出來的 1, 2, 3, 4, 5, 6, 數字 (Ctrl + G)
在調用語句之前使用關鍵字call
並將所有參數放在括號內,如下所示:
call MySub ("sth", Cvar(Array(1, 2, 3, 4, 5, 6)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.