为什么这段代码不能打开已经选中了项目的表单?我使用此代码将选择标志设置为true。
Private Sub UserForm_Initialize()
Dim i, InStrRes, k
With ActiveCell
If .Value <> "" Then
For i = 0 To Me.lstDV.ListCount - 1
InStrRes = InStr(1, ActiveCell.Value, Me.lstDV.List(i))
If InStrRes <> 0 And InStrRes <> Null Then
Me.lstDV.Selected(i) = True
End If
Next i
End If
End With
End Sub发布于 2020-04-27 09:35:29
Private Sub UserForm_Initialize()
Dim i, InStrRes, k
With ActiveCell
If .Value <> "" Then
For i = 0 To Me.lstDV.ListCount - 1
Me.lstDV.Selected(i) = False '<~~ add this code. Should be set to false in advance.
InStrRes = InStr(1, ActiveCell.Value, Me.lstDV.List(i))
'If InStrRes <> 0 And InStrRes <> Null Then
If InStrRes Then
Me.lstDV.Selected(i) = True
End If
Next i
End If
End With
End Sub发布于 2020-04-27 09:58:38
必须假定列表框在初始化时尚未加载。我尝试了Activate事件,但同样没有成功。请尝试此代码。
Sub ShowMyForm()
Dim MyForm As New TryForm
Dim CellVal As Variant
CellVal = ActiveCell.Value
With MyForm
If Len(CellVal) Then
On Error Resume Next
.lstDV.ListIndex = Application.Match(CellVal, Range(.lstDV.RowSource), 0) - 1
End If
.Show
' code continues here when the form is closed
End With
Unload MyForm
End Sub此代码必须在标准代码模块中,而不是窗体的代码表中。它调用表单TryForm (替换为您为表单指定的名称),并在显示之前对其进行修改。请注意,您仍然可以完全访问窗体,以便在窗体被隐藏后取出您可能需要的值。只需避免在表单代码中的任何地方使用Unload Me,因为卸载是由上面的代码在您获取所需的所有内容之后完成的。
请注意,表单的Initialize事件在您获得访问权限之前很久就由Dim MyForm As New TryForm中的New关键字触发。激活事件之后会有一些延迟。请确保您可能使用这些事件运行的过程不会干扰上述代码所做的工作。
https://stackoverflow.com/questions/61450018
复制相似问题