访问VBA类数组

时间:2013-06-05 16:34:28

标签: class vba service web module

我试图使用一些可以保存发票数据的类,我似乎无法使其正常工作。我只是想让它在数组中保存发票的详细信息。下面是代码,也许有人可以搞清楚。 也喜欢LineItems采取随机数量的产品项目,不知道如何做到这一点。我这样做最终通过ms访问从Web服务发送数据。

这是struct_XOrder的其他代码:

Public OrderNumber As String 
Public ClientShortName As String 
'"LineItems" is an array with elements defined as struct_LineItem
'See Complex Types: Arrays in Microsoft Office 2003 Web Services Toolkit Help
'for details on implementing arrays.
Public LineItems As Variant 
Public OrderError As String 

继承了struct_LineItem:

Public ProductSKU As String 
Public Qty As Long 
Public UnitPrice As Variant 
Public ItemComment As String 
Public ItemError As String

继承我的主要代码

Sub webservicetest()

Dim NewOrder As struct_XOrder
Dim LineItems(1 To 2) As Variant
Dim Xline(1 To 2) As Variant

Set Xline() = struct_LineItem

Set NewOrder = New struct_XOrder

Set NewOrder.LineItems() = New struct_LineItem
Set NewOrder.LineItems() = New Xline
'Xline = New struct_LineItem


Xline(1).ItemComment = "items" 
Xline(1).Qty = 10
NewOrder.LineItems() = Xline()


NewOrder.ClientShortName = "DemoClient"
NewOrder.OrderNumber = "12345"

'Xline(1).ItemComment = "item1"
'Xline(1).Qty = 5

Debug.Print NewOrder.ClientShortName
Debug.Print NewOrder.OrderNumber

'For i = LBound(Xline) To UBound(Xline): Debug.Print Xline(i): Next

'Debug.Print Xline(1).ItemComment
'Debug.Print Xline(1).Qty

End Sub

1 个答案:

答案 0 :(得分:1)

请参阅注释以获得解释。

在VBA中使用Type来创建结构。此外,您无需按照自己的方式使用Set

此外,使用Option Explicit在使用VBA时需要变量声明,除非你想要一场噩梦。

这一切都可以进入同一模块。


'use this
Option Explicit

'VBA structs are defined like the following
'and do not need "new" (similar to other languages)
'when creating them

Type struct_LineItem
    ProductSKU As String
    Qty As Long
    UnitPrice As Variant
    ItemComment As String
    ItemError As String

End Type

Type struct_XOrder
    OrderNumber As String
    ClientShortName As String

    'make this more clear
    LineItems() As struct_LineItem
    OrderError As String
End Type


Sub webservicetest()

    Dim NewOrder As struct_XOrder
    Dim LineItems(1 To 2) As Variant
    Dim Xline(1 To 2) As struct_LineItem

    'you can't do this, you need to specify which element
    'in XLine you want to set
    'Set Xline() = struct_LineItem

    Dim myStruct As struct_LineItem
    Xline(1) = myStruct

    'you don't need "set"
    NewOrder.LineItems = Xline()

    'this won't update as if it's a reference, btw
    Xline(1).ItemComment = "items"
    Xline(1).Qty = 10
    NewOrder.LineItems = Xline()


    NewOrder.ClientShortName = "DemoClient"
    NewOrder.OrderNumber = "12345"

    Debug.Print NewOrder.ClientShortName
    Debug.Print NewOrder.OrderNumber

    'don't do ":" as this makes code unbearably not readable...
    'For i = LBound(Xline) To UBound(Xline): Debug.Print Xline(i): Next

    Dim i As Integer
    For i = 1 To UBound(NewOrder.LineItems)
        Debug.Print NewOrder.LineItems(i).ItemComment
    Next i

End Sub