gpt4 book ai didi

class - 在 VBA 中使用自定义数据类型

转载 作者:行者123 更新时间:2023-12-01 16:25:45 24 4
gpt4 key购买 nike

我正在尝试在 VBA for Excel 中创建自定义数据类型。我们称这种数据类型为“卡车”。每辆卡车都有以下属性:

NumberOfAxles (this is an integer)
AxleWeights (this is an array of doubles)
AxleSpacings (this is an array of doubles)

我可以创建数据类型“truck”的多个实例(truck(1)、truck(2)...等),并将上面列出的属性读/写到该实例吗?

示例:

Truck(1).NumberOfAxles = 2
Truck(1).AxleWeights(1) = 15.0
Truck(1).AxleWeights(2) = 30.0
Truck(1).AxleSpacings(1) = 8.0

Truck(2).NumberOfAxles = 3
Truck(2).AxleWeights(1) = 8.0
Truck(2).AxleWeights(2) = 10.0
Truck(2).AxleWeights(3) = 12.0
Truck(2).AxleSpacings(1) = 20.0
Truck(2).AxleSpacings(2) = 4.0

等等。上面的语法很可能是错误的,我只是想演示我需要提出的结构。

我正在尝试将数据写入数据结构并根据需要调用它,例如

Truck(i).NumberOfAxles
Truck(i).AxleWeights(j)
Truck(i).AxleSpacings(j)

非常感谢!

最佳答案

当然可以:

Option Explicit

'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType

MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3

Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer

MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333

For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub

关于class - 在 VBA 中使用自定义数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12414168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com