1

我试图使用一些将保存发票数据的类,但我似乎无法让它工作。我只是希望它将发票的详细信息保存在数组中。这是代码,也许有人可以弄清楚。也喜欢 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
4

1 回答 1

1

请参阅评论以获取解释。

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

此外,在使用 VBA 时使用 Option Explicit 来要求变量声明,除非您想要做噩梦。

这一切都可以放在同一个模块中。


'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
于 2013-06-05T16:45:29.447 回答