我这里有另一个表单,在初始化期间显示 Sheet1 的数据。当有 Listbox 项目选择或 Listbox afterupdate 事件时,列表框会从 Sheet2 返回文本字段中选定数字(以字母 D 表示)的值:
工作表1
一个 | 乙 | 碳 | 德 |
---|---|---|---|
数字 | 日期1 | 日期2 | 版本 |
D-12300 | 2025 年 3 月 16 日 | 2025 年 3 月 16 日 | 1-50-02 |
D-12347 | 2025 年 3 月 17 日 | 2025 年 3 月 17 日 | 1-50-03 |
D-12348 | 2025 年 3 月 18 日 | 2025 年 3 月 18 日 | 1-50-04 |
工作表2
一个 | 乙 | 碳 | 德 |
---|---|---|---|
数字 | 描述 | 日期 | 版本 |
D-12345 | 描述1 | 2025 年 2 月 15 日 | 1-50-01 |
D-12346 | 描述1 | 2025 年 3 月 16 日 | 1-50-02 |
D-12347 | 描述2 | 2025 年 3 月 17 日 | 1-50-03 |
D-12348 | 描述3 | 2025 年 3 月 18 日 | 1-50-04 |
D-12349 | 描述1 | 2025 年 3 月 19 日 | 1-50-05 |
列表框1
Private Sub ListBox1_AfterUpdate()
Me.txtSheet1Digits.Value = ""
Me.txtSheet1Date1.Value = ""
Me.txtSheet1Date2.Value = ""
Me.txtSheet1Version.Value = ""
Me.txtSheet1Digits = ListBox1.Column(0)
Me.txtSheet1Date1 = ListBox1.Column(1)
Me.txtSheet1Date2 = ListBox1.Column(2)
Me.txtSheet1Version = ListBox1.Column(3)
Matches
End Sub
上一篇文章中使用的代码片段:
Sub Matches()
Dim ws2 As Worksheet: Set ws2 = Worksheets("Sheet2")
Dim i As Long
Dim arr: arr = ws2.Range("A1").CurrentRegion.Value
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim targetDate As Variant
Dim targetVersion As Variant
For i = 2 To UBound(arr)
dict(arr(i, 1)) = Empty
Next
If dict.exists(Me.txtSheet1Digits.Value) Then
targetDate = Application.VLookup(Me.txtSheet1Digits.Value, ws2.Range("B1").CurrentRegion.Value, 3, False)
targetVersion = Application.VLookup(Me.txtSheet1Digits.Value, ws2.Range("B1").CurrentRegion.Value, 4, False)
Me.txtSheet2Date = targetDate
Me.txtSheet2Version = targetVersion
End If
If Not Me.txtSheet1Date1 = Me.txtSheet2Date Or _
Not Me.txtSheet1Version = Me.txtSheet2Version Then
labelSheet1Date1.ForeColor = vbRed
txtSheet1Date1.ForeColor = vbRed
labelSheet1Date2.ForeColor = vbRed
txtSheet1Date2.ForeColor = vbRed
labelSheet2Date.ForeColor = vbRed
txtSheet2Date.ForeColor = vbRed
labelSheet1Version.ForeColor = vbRed
txtSheet1Version.ForeColor = vbRed
labelSheet2Version.ForeColor = vbRed
txtSheet2Version.ForeColor = vbRed
Else
labelSheet1Date1.ForeColor = vbBlack
txtSheet1Date1.ForeColor = vbBlack
labelSheet1Date2.ForeColor = vbBlack
txtSheet1Date2.ForeColor = vbBlack
labelSheet2Date.ForeColor = vbBlack
txtSheet2Date.ForeColor = vbBlack
labelSheet1Version.ForeColor = vbBlack
txtSheet1Version.ForeColor = vbBlack
labelSheet2Version.ForeColor = vbBlack
txtSheet2Version.ForeColor = vbBlack
End If
End Sub
我只是想知道以下错误可能是什么:
当我单击列表框中的第一个项目时,它会读取第一个 If 条件,而 Sheet2 中没有任何匹配项,这是正确的,并将空白返回到两个文本字段。接下来,它读取第二个条件,此时所有条件都变为红色 - 正确。
当我单击列表框的第二项时,读数相同,并且现在转到第二个 If 条件的其他条件,因此它全是黑色 - 正确。
现在,当我再次单击返回到第一个项目时,它会读取相同的模式,但不会再向两个文本字段返回空白。带有箭头的两个文本字段继续具有先前选定项目的值 - 错误。它应该返回空白。
如果 Sheet2 中没有匹配项,则添加
Else
子句来清除文本框。在事件中始终初始化两个文本框
AfterUpdate
。