VBA函数返回集合

时间:2018-03-14 16:50:54

标签: vba excel-vba excel

我试图从函数返回类型Collection,我收到错误:

  

编译错误:

     

无效使用财产

以下是我为测试该功能而创建的以下代码。我知道这个集合正在填充,因为我正在测试集合的运行并输出所有值;这一切都按照预期出现。

问题:

为什么会出现此错误?什么是解决它的最佳方法?

Sub testingFunc()

   Dim ErrorCodes As Collection
   Set ErrorCodes = New Collection

   Set InitializeErrorCodes = ErrorCodes '<--- Where my error is occurring when trying to retrieve the collection

End Sub

这是初始化我的Error Codes

的代码
Function InitializeErrorCodes() As Collection '<--- Where I'm trying to return the collection

   Dim ErrorCodes As Collection
   Set ErrorCodes = New Collection

   AddToErrorCollection ErrorCodes, "CSD_ERR_120", "Multiple products in a case is invalid"
   AddToErrorCollection ErrorCodes, "CSD_ERR_128", "Invalid Store with Zero Allocation"
   AddToErrorCollection ErrorCodes, "DET_ERR_101", "Purchase Order Status Notification"
   AddToErrorCollection ErrorCodes, "DET_ERR_104", "Tolerance Violation - Overshipment"
   AddToErrorCollection ErrorCodes, "DET_ERR_110", "Multiple Open Lines found for Product on PO"
   AddToErrorCollection ErrorCodes, "DET_ERR_111", "Tolerance Violation - short shipment"
   AddToErrorCollection ErrorCodes, "DET_ERR_112", "Tolerance Violation - Number of Store/SKU Discrepancies Exceeded"
   AddToErrorCollection ErrorCodes, "DET_ERR_114", "Product (casepack) Mismatch on one or more product identifiers"
   AddToErrorCollection ErrorCodes, "DET_ERR_115", "Product (Bulk) Mismatch on one or more product indentifiers"
   AddToErrorCollection ErrorCodes, "DET_ERR_116", "No Open Line was found. PO contains a line in Cancel Status for Product"
   AddToErrorCollection ErrorCodes, "DET_ERR_117", "Early Shipping Date Violation"
   AddToErrorCollection ErrorCodes, "DET_ERR_118", "PO Cancel Date Violation || Passed Cancel Date"
   AddToErrorCollection ErrorCodes, "DET_ERR_125", "Duplicate vendor case number"
   AddToErrorCollection ErrorCodes, "HDR_ERR_101", "Duplicate Vendor ASN Number"
   AddToErrorCollection ErrorCodes, "PRE_ERR_105", "Invalid Prepack configuration. Failed - Missing Component SKU(s)"
   AddToErrorCollection ErrorCodes, "PRE_ERR_106", "Product Quantity does not equal the sum of the case quantities"

   Set InitializeErrorCodes = ErrorCodes

End Function

以下是与上述相关的功能,以添加到集合

Private Sub AddToErrorCollection(Col As Collection, eName As String, eDescription As String)

   Dim NewErrorCode As cErrorCodes
   Set NewErrorCode = New cErrorCodes
   NewErrorCode.name = eName
   NewErrorCode.description = eDescription

   Col.Add NewErrorCode

End Sub

1 个答案:

答案 0 :(得分:2)

InitializeErrorCodes是一个函数,而不是属性,但您尝试将其用作属性。 正确的电话应该是Set ErrorCodes = InitializeErrorCodes

由于InitializeErrorCodes执行集合初始化,您应该将Set ErrorCodes = New Collection放在testingFunc中。