You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于默认值对存储自定义类对象的VBA ArrayList排序?

VBA中基于自定义类默认属性对ArrayList排序的解决方案

问题背景

使用System.Collections.ArrayList存储自定义类IdContainer对象,该类包含.text(默认属性)和.time等属性,目标是利用ArrayList的Sort方法基于.text排序。但遇到两个问题:

  • 直接添加IdContainer对象到ArrayList时,会自动提取默认属性.text存入字符串而非对象;
  • 即使成功存入对象,Sort方法无法识别默认属性,排序不生效。

原代码中采用先添加空IdContainer对象再替换指针的方式存入对象:

Private id As IdContainer 
Set id = New IdContainer
id = textbuffer ' 利用默认属性赋值.text
id.time = Time  

' 存入ArrayList的操作
DevIdArray.Add (New IdContainer) ' 因加括号,实际存入的是空对象的默认属性(空字符串)
Set DevIdArray.Item(DevIdArray.Count - 1) = id ' 替换为实际对象指针
Set id = Nothing

解决方案

1. 简化对象存入方式

VBA中调用ArrayList.Add时,若参数加括号会强制求值提取默认属性,导致存入字符串而非对象。直接去掉括号即可存入对象,无需先加空对象再替换:

Private id As IdContainer 
Set id = New IdContainer
id = textbuffer
id.time = Time  

DevIdArray.Add id ' 直接存入对象,无需括号
Set id = Nothing

2. 让自定义类实现IComparable接口

ArrayList的Sort方法依赖元素实现IComparable接口来定义比较逻辑,只需给IdContainer类添加该接口的实现,即可基于.text属性排序。

在IdContainer类模块中添加以下代码:

Implements IComparable

' 实现IComparable的CompareTo方法
Private Function IComparable_CompareTo(ByVal obj As Variant) As Long
    Dim otherId As IdContainer
    Set otherId = obj ' 转换为自定义类类型
    
    ' 基于.text属性进行字符串比较,返回比较结果
    IComparable_CompareTo = StrComp(Me.text, otherId.text, vbTextCompare)
    ' 若需区分大小写,改为vbBinaryCompare
End Function

' 保持原有的默认属性定义(假设你已经设置了.text为默认属性)
Private m_text As String
Public Property Get text() As String
    text = m_text
End Property

Public Property Let text(ByVal newValue As String)
    m_text = newValue
End Property

' 其他属性如.time的定义
Public time As Date

3. 执行排序

完成上述修改后,直接调用ArrayList.Sort即可基于.text属性排序:

DevIdArray.Sort

这样既解决了对象存入的问题,又无需自行编写排序算法,直接利用ArrayList内置的Sort功能实现需求。

内容的提问来源于stack exchange,提问作者Asdf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:47:25