【问题标题】:User defined type variable用户定义类型变量
【发布时间】:2020-08-10 13:45:56
【问题描述】:

我正在尝试编写 3 个用户定义的类型变量,它们需要像这样相互关联;

Type tdrivers 
    Strfirstname as string
    Strsurname as string 
    Intage as integer
End type

Type Tcars 
     Strmake as string 
     Strmodel as string 
     Lngcc as long
     Driverid() as tdrivers
End type

Type T_Race
     Strlocation as string 
     DteRacedate as date
     IntYear as integer
     CarsID() as Tcars
End Type

Sub CreateRace()

Dim myrace() as T_Race

'Variables to hold integer 'values at runtime
Dim A as integer 
Dim B as integer
Dim C as integer 

'this line redims myrace ok
Redim myrace(A) 

'This line doesn't do anything 
'When I try to redim the 'carsID() array nested inside 'the myrace(A) like so;
Redim myrace(A).carsID(B)

'This line obviously does 'nothing either 
Redim myrace(A).CarsID(B).driverid(C)

我需要能够将比赛分配给 myrace() 数组,然后将赛车分配给他们参加的每场比赛,然后将车手分配给他们驾驶的赛车。所以carsID() 必须嵌套在myrace() 中,而driverid() 必须嵌套在carsID() 中

一旦我知道如何在其中重新调整carsID(),就可以重新调整嵌套在其中的Driverid()。

如果我将所有数组固定为一个常数值,例如 8,那么子程序运行正常,所有比赛、汽车和车手都正确嵌套。它对嵌套动态数组的 redim 失败了。希望这是有道理的。任何人都可以帮忙。谢谢

【问题讨论】:

  • 在您尝试 ReDim 之前,A、B 是否有值?在 ReDim x(0) 之后你会期待什么?
  • 是的,A、B 和 C 变量都在 redim 完成之前分配了值。只有 myrace(A) 会自行重新调整尺寸,但会在以下情况下失败;
  • 继续。 CarsID(B) 像这样嵌套时不会重新调整尺寸; redim myrace(A).carsID(B)

标签: excel vba


【解决方案1】:

关键是你必须单独ReDim 每个 子数组。以下示例初始化所有子数组并在最后打印它们:

Sub Example()
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    
    ReDim myRace(5)
    
    For i = 1 To 5
        ReDim myRace(i).CarsID(5)
        For j = 1 To 5
            ReDim myRace(i).CarsID(j).Driverid(5)
            For k = 1 To 5
                myRace(i).CarsID(j).Driverid(k).Strfirstname = Chr(k + Asc("a")) & Str(i) & Str(j) & Str(k)
            Next k
        Next j
    Next i
    
    ' Now print it
    For i = 1 To 5
        For j = 1 To 5
            For k = 1 To 5
                Debug.Print myRace(i).CarsID(j).Driverid(k).Strfirstname
            Next k
        Next j
    Next i
        
End Sub

【讨论】:

  • 现在说得通了。非常感谢您的回复以及您举例说明的方式。回去工作的时候我会试试的。再次非常感谢,感谢上帝让像你这样的专家为像我这样的新手提供实际示例的帮助,大多数网站在学习时并没有完全解释所有内容。
  • @RichieG 记得标记答案,如果它对你有帮助,以便其他人也能找到它
  • 使代码完全可重现的友好提示:所有三个数组声明都应插入到示例过程中或模块声明头中(Dim myrace() As T_RaceDim CarsID As Tcars 以及 Dim DriverID As tdrivers): +)
  • Paul ogilvie,你对我的问题的例子。当您对每个子数组进行 redim 时,您是否需要使用保留 redim 而不仅仅是 redim。当然,如果您只是单独 redim,那么在遍历数组元素时,每个先前的元素都会丢失吗?
  • @RichieG,抱歉我的回复晚了。如果数组包含数据,那么您应该使用Redim ... Preserve 这样现有的数据将被保留。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2013-02-25
  • 1970-01-01
相关资源
最近更新 更多