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

VBA用户表单多次点击按钮时Dictionary无法留存数据的解决方法

解决Dictionary每次点击按钮被清空的问题

你的问题核心原因很明确:每次点击"Add pipe"按钮时,都执行了Set myDic = New Dictionary,这会重新创建一个空字典,之前存储的所有数据都会被清空。

修正步骤

  1. 将字典的实例化操作移到表单的初始化事件中,确保字典只在表单加载时创建一次,而不是每次点击按钮都重建。
  2. 修复check_button_Click中的变量未初始化问题,避免写入Excel单元格时出现位置错误。

修正后的完整代码

Public myDic As Dictionary
Dim diam As Single, myLen As Single
Dim a As Boolean

Private Sub UserForm_Initialize()
    ' 仅在表单加载时初始化字典一次
    Set myDic = New Dictionary
    myDic.CompareMode = vbTextCompare
End Sub

Private Sub button_add_Click()
    a = False
    diam = f_diam.Value ' 获取用户表单输入的直径
    myLen = f_len.Value ' 获取用户表单输入的长度
    comparador = "DN" & diam & "*"
    tramo = "DN" & diam & " - " & myLen & " m"
    
    ' 检查ListBox中是否已存在该直径
    For i = 0 To ListBox.ListCount - 1
        If ListBox.List(i) Like comparador Then
            a = True
            pregunta = MsgBox("DN" & diam & " 已存在。" & vbCrLf & "是否用新长度更新它?", vbYesNo + vbExclamation, "MOS-Database - 覆盖确认?")
            If pregunta = vbYes Then
                ListBox.List(i) = tramo ' 更新ListBox条目
                myDic.Item(diam) = myLen ' 更新字典中的对应值
                Exit For
            Else
                Exit Sub
            End If
        End If
    Next i
    
    ' 如果不存在,则添加到ListBox和字典
    If a = False Then
        ListBox.AddItem tramo
        myDic.Add Key:=diam, Item:=myLen
    End If
End Sub

Private Sub check_button_Click()
    Dim i As Integer ' 显式声明变量
    i = 0 ' 初始化行号
    
    For Each Key In myDic.Keys
        Sheets("Prueba").Cells(i + 1, 1) = Key
        Sheets("Prueba").Cells(i + 1, 2) = myDic(Key)
        i = i + 1 ' 行号递增
    Next Key
End Sub

关键修改说明

  • 把Set myDic = New Dictionary和myDic.CompareMode = vbTextCompare移到UserForm_Initialize事件,确保字典在表单生命周期内只创建一次,数据会持续留存。
  • 在check_button_Click中新增了变量i的声明和初始化,避免因变量未赋值导致的写入位置错误。

内容的提问来源于stack exchange,提问作者Irene Ortiz de Guzmán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:45:36