如何基于Excel工作表列填充userform的combobox 仅保留最新版工装编号
实现逻辑
- 遍历工装编号列,将每一个编号拆分为固定前缀和末尾版本字母两部分
- 用字典存储每个前缀对应的最新完整编号:同前缀下版本字母更靠后的判定为最新版本,覆盖旧版本记录
- 遍历完成后直接将字典存储的所有最新编号加载到ComboBox
示例代码
将以下代码添加到你的UserForm的Initialize事件中即可:
Private Sub UserForm_Initialize() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim toolNum As String, prefix As String, version As String Dim latestDict As Object ' 替换为你存储工装编号的工作表名称 Set ws = ThisWorkbook.Worksheets("Sheet1") ' 获取A列最后一行有数据的行号 lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' 创建字典存储前缀与对应最新版本 Set latestDict = CreateObject("Scripting.Dictionary") ' 遍历A列数据,默认第1行为表头,从第2行开始,按需调整起始行 For i = 2 To lastRow toolNum = Trim(ws.Cells(i, "A").Value) If toolNum <> "" Then ' 拆分前缀和版本:末尾1位为版本字母,剩余部分为固定前缀 prefix = Left(toolNum, Len(toolNum) - 1) version = Right(toolNum, 1) If Not latestDict.Exists(prefix) Then ' 前缀首次出现直接存入 latestDict.Add prefix, toolNum Else ' 同前缀对比版本,字母越靠后版本越新,替换旧版本 If version > Right(latestDict(prefix), 1) Then latestDict(prefix) = toolNum End If End If End If Next i ' 将所有最新版本加载到ComboBox,修改ComboBox1为你的控件实际名称 Me.ComboBox1.List = latestDict.Items End Sub
适配调整说明
- 如果你的版本号是固定多位字母(比如2位:
XXX001AB比XXX001AA版本新),修改拆分逻辑即可:prefix = Left(toolNum, Len(toolNum) - 2),version = Right(toolNum, 2) - 如果存在无版本后缀的纯数字编号,可新增判断逻辑:如果末尾字符不是字母,直接将完整编号作为前缀存入字典
- 如果版本更新规则不是字母升序,调整版本对比的判断条件即可
内容的提问来源于stack exchange,提问作者inmoint
相关产品推荐
相关产品推荐

